UIWebView 是在 App 內嵌入網頁內容的經典元件。本文從載入網頁出發,逐步示範如何透過 delegate 掌握載入狀態、顯示等待動畫,並在出錯時給予提示。
開啟 Xcode,新增一個名為 WebViewDemo 的 Single View Application。

在 ViewController.h 宣告 WebView 成員變數,並在 ViewController.m 中實作:
@interface ViewController : UIViewController
{
UIWebView *webView;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[self.view addSubview:webView];
[webView loadRequest:request];
}
執行後,百度網頁就打開了:

手機的網路環境瞬息萬變。網路慢時如何提示「正在載入」?出錯時如何提示使用者?這就需要知道網頁何時開始載入、何時完成、何時出錯。我們可以實作 UIWebViewDelegate 協定:
@interface ViewController : UIViewController{ UIWebView *webView; } @end
按住 control + command + 向上鍵切換到 .m 檔,輸入 - (void) webView 就能看到官方提供的 delegate 方法清單:

1、webViewDidStartLoad:——開始載入時呼叫。
2、webViewDidFinishLoad:——載入完成時呼叫。
3、webView:didFailLoadWithError:——載入出錯時呼叫。
我們可以把載入指示器(activityIndicatorView)放進前兩個方法:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[activityIndicatorView startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicatorView stopAnimating];
}
按下按鈕時,呼叫載入網頁的方法:
- (IBAction)buttonPress:(id)sender
{
[textField resignFirstResponder];
[self loadWebPageWithString:textField.text];
}
請求出錯時,用 UIAlertView 給予提示:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@""
message:[error localizedDescription] delegate:nil
cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alterview show];
[alterview release];
}
為了給使用者更友善的視覺回饋,我們在開始載入時疊加一個半透明背景與轉圈動畫:
- (void)webViewDidStartLoad:(UIWebView *)webView
{
// 建立半透明背景
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[view setTag:108];
[view setBackgroundColor:[UIColor blackColor]];
[view setAlpha:0.5];
[self.view addSubview:view];
activityIndicator = [[UIActivityIndicatorView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
[activityIndicator setCenter:view.center];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
[view addSubview:activityIndicator];
[activityIndicator startAnimating];
}
載入完成或失敗時,移除等待畫面:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];
}
執行後即可看到載入時的等待動畫效果:

透過 delegate 掌握載入生命週期,再搭配等待動畫與錯誤提示,就能打造流暢、友善的 WebView 瀏覽體驗。