WKWebview加載富文本(本地HMTL)可能會(huì)出現(xiàn)一些布局問(wèn)題,圖片大小不對(duì)、位置不對(duì)、字體大小不對(duì)等等,這主要是HMTL沒(méi)有傳入樣式,所以需要我們?cè)诩虞dwebview的時(shí)候注入一段JS代碼。這樣就能完美解決布局錯(cuò)亂問(wèn)題。
直接上代碼:
NSString *jScript =
@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content','width=device-width,initial-scale=1.0');document.getElementsByTagName('head')[0].appendChild(meta);var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].setAttribute('width', '100%');imgs[i].style.height='auto';}";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
[_webView loadHTMLString:htmlStr baseURL:nil];
對(duì)比如下:

未注入JS代碼前

注入JS代碼后
如有問(wèn)題請(qǐng)留言哦~~