WKWebview加載富文本(本地HMTL)可能會出現(xiàn)一些布局問題,圖片大小不對、位置不對注暗、字體大小不對等等,這主要是HMTL沒有傳入樣式撕攒,所以需要我們在加載webview的時(shí)候注入一段JS代碼。這樣就能完美解決布局錯(cuò)亂問題。
直接上代碼:
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];
對比如下:
未注入JS代碼前
注入JS代碼后
如有問題請留言哦~~