首先解決自適應(yīng)屏幕寬度的問題
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
WKUserContentController *content = [[WKUserContentController alloc]init];
// 自適應(yīng)屏幕寬度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];
// 添加自適應(yīng)屏幕寬度js調(diào)用的方法
[content addUserScript:wkUserScript];
wkWebConfig.userContentController = content;
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth , 0) configuration:wkWebConfig];
webView.scrollView.bounces = NO;
webView.UIDelegate = self;
webView.navigationDelegate = self;
webView.scrollView.scrollEnabled = NO;
self.webView = webView;
[self.mainScrollView addSubview:webView];
其次計算高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//修改字體大小 300%
// [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
//修改字體顏色 #9098b8
// [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#0078f0'" completionHandler:nil];
__block CGFloat webViewHeight;
//獲取內(nèi)容實際高度(像素)@"document.getElementById(\"content\").offsetHeight;"
[webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
// 此處js字符串采用scrollHeight而不是offsetHeight是因為后者并獲取不到高度,看參考資料說是對于加載html字符串的情況下使用后者可以(@"document.getElementById(\"content\").offsetHeight;"),但如果是和我一樣直接加載原站內(nèi)容使用前者更合適
//獲取頁面高度,并重置webview的frame
webViewHeight = [result floatValue];
webView.height = webViewHeight;
self.mainScrollView.contentSize = CGSizeMake(KScreenWidth, webView.top + webViewHeight);
NSLog(@"%f",webViewHeight);
}];
}
如果加載HTML圖片的時候失敗,可能是info.plist文件沒加網(wǎng)絡(luò)權(quán)限
Allow Arbitrary Loads in Web Content
Allow Arbitrary Loads
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。