iOS使用WKWebView加載HTML5不顯示屏幕寬度的問題解決

這篇文章主要介紹了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寫的,調了半天結果就是不佔據屏幕寬度,好煩啊。(想對着自錘兩下)。找資料原來可以設一個屬性就可以解決,豪嗨心呀!

沒設置屬性之前是這個鬼樣子的

使用[_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;
}

到這裏適配一下就好了,看效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章