我想将活动指示符添加到Web视图。 但我不知道web视图何时完成加载。 我在viewdidload中开始制作动画..
答案 0 :(得分:19)
您不应该在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
答案 1 :(得分: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
答案 2 :(得分:2)
您需要侦听网络视图委托回调以正确显示您的活动指示符。
具体来说,你会想听:
webViewDidStartLoad :(开始您的活动指标动画)
webViewDidFinishLoad :(结束它)
webView:didFailLoadWithError :(结束它)
答案 3 :(得分:0)
- (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;
}