UIWebView 雖然在後續的 iOS 版本中被 WKWebView 取代,但它仍是理解 iOS 內嵌網頁機制的最佳起點,早期大量 App 的「網頁型頁面」都建立在它之上。本文從最基礎的載入寫法開始,再整理三個實戰中經常派上用場的技巧。
- (void)viewDidLoad {
[super viewDidLoad];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenHeight - 20)];
webView.scalesPageToFit = YES; // 自動縮放以適應螢幕
webView.userInteractionEnabled = YES;
webView.opaque = YES;
[self.view addSubview:webView];
NSURL *url = [NSURL URLWithString:@"https://www.youku.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
// 也可以直接載入 HTML 字串
// NSString *myHT = @"優酷";
// [webView loadHTMLString:myHT baseURL:url];
// 瀏覽控制
// [webView goBack]; // 返回
// [webView goForward]; // 前往
// [webView reload];
// [webView stopLoading];
webView.delegate = self;
// 移除滾動時出現的外圍陰影
UIScrollView *scrollView = webView.scrollView;
for (int i = 0; i < scrollView.subviews.count; i++) {
UIView *view = [scrollView.subviews objectAtIndex:i];
if ([view isKindOfClass:[UIImageView class]]) {
view.hidden = YES;
}
}
}
接著實作 UIWebViewDelegate,把網頁生命週期中的關鍵節點掌握在手裡:
#pragma mark - UIWebViewDelegate
// 即將開始載入,回傳 NO 可攔截請求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
/**
typedef NS_ENUM(NSInteger, UIWebViewNavigationType) {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
*/
NSLOG_FUNCTION;
return YES;
}
// 開始載入
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLOG_FUNCTION;
}
// 載入完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLOG_FUNCTION;
}
// 載入失敗,彈出錯誤提示
- (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];
NSLOG_FUNCTION;
}
直接載入 PC 版網站時,內容往往會溢出螢幕可視範圍,版面顯得又小又難讀。解法是在 webViewDidFinishLoad: 中,用 JavaScript 動態改寫頁面既有的 viewport meta 標籤:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *meta = [NSString stringWithFormat:
@"document.getElementsByName(\"viewport\")[0].content = "
"\"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"",
IPHONE_WIDTH];
[webView stringByEvaluatingJavaScriptFromString:meta];
}
使用這個技巧時務必把 scalesPageToFit 設為 NO,否則兩套縮放機制會互相打架:
webView.scalesPageToFit = NO;
思路並不複雜:為每個 img 標籤掛上 onclick,在事件裡把圖片網址包成一個自訂協定的 URL,再由原生端攔截這個特殊請求,就能取得圖片位置並自行決定後續行為(例如另開一個全屏預覽頁)。
如果是用 loadHTMLString 載入,可以在字串上做替換:
html = [html stringByReplacingOccurrencesOfString:@"<img "
withString:@"<img onclick=\"window.location.href=('https://src.'+this.src);\" "];
如果是用 loadRequest,則改在 webViewDidFinishLoad: 中注入 JS:
NSString *js = @"var imgs = document.getElementsByTagName(\"img\");"
"for(var i=0;i<imgs.length;i++){"
" var img = imgs[i];"
" img.onclick=function(){window.location.href=('https://src.'+this.src);}"
"}";
[webView stringByEvaluatingJavaScriptFromString:js];
最後在代理方法裡攔截,把前綴去掉就得到真正的圖片網址:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSString *url = request.URL.absoluteString;
if ([url hasPrefix:@"https://src."]) {
url = [url stringByReplacingOccurrencesOfString:@"https://src." withString:@""];
// 在這裡處理圖片,例如開啟大圖瀏覽
return NO;
}
return YES;
}
UIWebView 內部包著一個 scrollView,只要往這個 scrollView 塞入一個 y 座標為負的子視圖,並同步調整 contentInset 把空間讓出來,就能得到一個跟著內容一起捲動的自訂頁頭:
CGFloat headerHeight = 36.0f; // 注意:y 座標必須是負值,IPHONE_WIDTH 為螢幕寬度
UIView *headerView = [[UIView alloc] initWithFrame:
CGRectMake(0, -headerHeight, IPHONE_WIDTH, headerHeight)];
[_webView.scrollView addSubview:headerView];
// 調整 contentInset,讓頂部空出足夠空間
UIEdgeInsets edgeInset = _webView.scrollView.contentInset;
_webView.scrollView.contentInset = UIEdgeInsetsMake(headerView.frameHeight,
edgeInset.left,
edgeInset.bottom,
edgeInset.right);
把這三個技巧串起來,一個堪用的「App 內瀏覽器」雛形就完成了。若要在新專案中使用,建議直接改用 WKWebView,它在記憶體管理與執行緒模型上都更優秀。