将活动指示符添加到Web视图

use*_*286 2 webview uiactivityindicatorview ios

我想在Web视图中添加活动指示器.但我不知道web视图何时完成加载.我开始在viewdidload动画..

小智 19

您不应该在viewDidLoad中开始制作动画.符合

UIWebViewDelegate
Run Code Online (Sandbox Code Playgroud)

协议并使您的Web视图委托您的视图控制器,然后使用委托方法:

@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
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,在`didFailLoadWithError`中,如果你想要做一些类似的事情告诉用户一些网页浏览问题,值得注意的是`error.code == NSURLErrorCancelled`并不是一个致命的错误,而是一个表明` UIWebView`将尝试转到另一个页面(因为用户在加载过程中点击链接,或者有时甚至因为网站本身正在重定向用户).简而言之,如果你打算在`didFailLoadWithError`中做更全面的事情,你可能想检查`error.code!= NSURLErrorCancelled`. (7认同)

Mid*_* MP 5

实现UIWebViewDelegate协议这些是您需要在代码中实现的委托:

- (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
Run Code Online (Sandbox Code Playgroud)