2012-07-04 54 views

回答

19

你不應該開始viewDidLoad中動畫。順應

UIWebViewDelegate 

協議,能讓您的網絡視圖的委託您的視圖控制器,然後使用委託方法:

@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 
+7

順便說一句,在'didFailLoadWithError'中,如果你曾經想做一些類似的事情來告訴用戶一些網頁瀏覽問題,值得注意的是'error.code == NSURLErrorCancelled'不是一個致命錯誤,而是一個指示UIWebView將嘗試轉到另一個頁面(或者是因爲用戶在加載過程中點擊鏈接,有時甚至是因爲網站本身正在重定向用戶)。總之,如果你打算在'didFailLoadWithError'中做更全面的事情,你可能想檢查'error.code!= NSURLErrorCancelled'。 – Rob

+0

是的,但它不是OP問題的一部分。 – 2012-07-05 05:41:56

+0

同意。沒有打算批評。只需觀察user1502286就可以知道這些非常直觀的'UIWebViewDelegate'方法的奇怪小怪癖。 – Rob

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 
+0

感謝這幫助我。 – Shivaay

+0

如果我正在查看的網站有多個框架,這些功能會被多次觸發是否正常?這些函數如何才能觸發父窗口? – thefoyer

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; 
} 
相關問題