iOS使用WKWebView載入HTML5不顯示螢幕寬度的問題
最近在專案中我們的商品詳情頁是一個後臺返回的圖片標籤。需要我們自己去寫一個HTML5標籤進行整合,(相當於重新寫了一個HTML頁面)
:ok_hand:那就沒辦法了,我就自己寫一個標籤咯,應該不難吧。嘻嘻嘻嘻~~~~~
dispatch_async(dispatch_get_main_queue(), ^{ if(self.detailModel.details){ //這裡是自己寫的簡單的載入H5 NSString *header =@"<head><meta name=\viewport\content=\width=device-width, initial-scale=1.0, user-scalable=no\> <style>body,html{width: 100%;height: 100%;}*{margin:0;padding:0;}img{max-width:100%;display:block; width:auto; height:auto;}</style></head>"; NSString *html = [NSString stringWithFormat:@"<html>%@<body>%@</body></html>",header,self.detailModel.details]; [self.webView loadHTMLString:html baseURL:nil]; } });
得,那我就先用UIWebView寫的,調了半天結果就是不佔據螢幕寬度,好煩啊。(想對著自錘兩下)。找資料原來可以設一個屬性就可以解決,豪嗨心呀!

螢幕快照 2018-11-15 下午5.15.49.png
使用[_webView setScalesPageToFit:NO]; 這個屬性就好了,這個屬性的作用是是都縮放到螢幕大小。好了,UIWebView使用這個卻解決了。
///////////////////////..............................告一段落
但是WKWebView呢?因為一般H5載入需要一點點時間並且也想加一個進度條的效果,這樣體驗會更加的好一點。當H5沒有載入完的時候使用者滑動頁面會卡住(因為scrollerView的ContentSize還不確定)。所以一般是在載入完成後再設定scrollerView的ContentSize。廢話不多說直接上程式碼
-(WKWebView *)webView { if (!_webView) { _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, iPhone5sHeight(375+135*PXSCALEH+285*PXSCALEH), screenW, screenH-50)]; WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init]; WKUserContentController *content = [[WKUserContentController alloc]init]; // 自適應螢幕寬度js NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; // 新增自適應螢幕寬度js呼叫的方法 [content addUserScript:wkUserScript]; wkWebConfig.userContentController = content; _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, iPhone5sHeight(375+135*PXSCALEH+285*PXSCALEH), screenW, screenH-50) configuration:wkWebConfig]; _webView.UIDelegate = self; _webView.navigationDelegate = self; } return _webView; }
到這裡適配一下就好了,看效果

螢幕快照 2018-11-15 下午5.16.55.png