我想将活动指示器添加到 Web 视图。但我不知道 Web 视图何时完成加载。我开始在视图加载中制作动画。
你不应该在viewDidLoad中开始制作动画。符合
UIWebViewDelegate
协议,并使 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
实现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
您需要侦听 Web 视图委托回调以正确显示活动指示器。
具体来说,您将需要收听:
webViewDidStartLoad:(启动您的活动指示器动画)
webViewDidFinishLoad: (end it)
webView:didFailLoadWithError: (end it)
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.webViewRef.delegate = self;
NSURL *websiteUrl = [NSURL URLWithString:Constants.API_TERMS_AND_CONDITIONS_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
[self.webViewRef loadRequest:urlRequest];
}
#pragma mark
#pragma mark -- UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
[self.activityIndicator startAnimating];
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
[self.activityIndicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self.activityIndicator stopAnimating];
self.activityIndicator.hidden = YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
[self.activityIndicator stopAnimating];
self.activityIndicator.hidden = YES;
}