Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add activity indicator to web view

I want to add activity indicator to a web view. But i don't know when web view finish loading. I start animating in viewdidload..

like image 340
user1502286 Avatar asked Mar 17 '26 14:03

user1502286


2 Answers

You shouldn't start animating in viewDidLoad. Conform to the

UIWebViewDelegate

protocol and make your web view's delegate your view controller, then use the delegate methods:

@interface MyVC: UIViewController <UIWebViewDelegate> {
    UIWebView *webView;
    UIActivityIndicatorView *activityIndicator;
}

@end

@implementation MyVC

- (id)init
{
    self = [super init];
    // ...

    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityIndicator.frame = CGRectMake(x, y, w, h);
    [self.view addSubview:activityIndicator];

    webView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, w, h)];
    webView.delegate = self;
    // ...
    return self;
}

- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)rq
{
    [activityIndicator startAnimating];
    return YES;
}

- (void)webViewDidFinishLoading:(UIWebView *)wv
{
    [activityIndicator stopAnimating];
}

- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error
{
    [activityIndicator stopAnimating];
}

@end

Implement the UIWebViewDelegate protocol These are the delegates you need to implement in your code:

- (void)webViewDidStartLoad:(UIWebView *)webView; //a web view starts loading
- (void)webViewDidFinishLoad:(UIWebView *)webView;//web view finishes loading
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; //web view failed to load
like image 40
Midhun MP Avatar answered Mar 20 '26 06:03

Midhun MP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!