ios UIWebview中網頁寬度自適應手機
阿新 • • 發佈:2019-01-03
有的網頁中會使用"<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">"這個標籤來設定網頁的寬度,不過帶來的問題是,如果展示這個webview的寬度不等於裝置的寬度的時候,就會出現網頁內容過寬左右可以滑動或者網頁左右內容沒有佔滿。找了一下,有兩個解決方法:
1. 利用webview中的scrollview的zoom特性,這個方法會讓網頁內容變小
2. 第二個方法,在客戶端使用js重寫meta標籤,這個也是在webview的delegate的webViewDidFinished回撥中呼叫;我們使用的這種方法來操作,內容不會變小- (void)webViewDidFinishLoad:(UIWebView *)theWebView { CGSize contentSize = theWebView.scrollView.contentSize; CGSize viewSize = self.view.bounds.size; float rw = viewSize.width / contentSize.width; theWebView.scrollView.minimumZoomScale = rw; theWebView.scrollView.maximumZoomScale = rw; theWebView.scrollView.zoomScale = rw; }
注:第二個方法我測試過不好用,大家用的時候還是測試一下吧javascript = [NSString stringWithFormat:@"var viewPortTag=document.createElement('meta'); \ viewPortTag.id='viewport'; \ viewPortTag.name = 'viewport'; \ viewPortTag.content = 'width=%d; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;'; \ document.getElementsByTagName('head')[0].appendChild(viewPortTag);" , (int)authWebView.bounds.size.width]; [authWebView stringByEvaluatingJavaScriptFromString:javascript];