使用WKWebView时,发现一个bug:“无论怎么修改htmlString中body的style都无效”,特此分享,代码如下:
- (void)initWebView:(NSString *)htmlString {
NSLog(@"字符HTML:%@", htmlString);
//注入JS以缩放网页,避免获取到的网页高度远超实际高度,出现超长空白页面
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
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;
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.webViewContent.frame.size.width, self.webViewContent.frame.size.height) configuration:wkWebConfig];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
self.webView.scrollView.delegate = self; // 监听捏合缩放
//开了支持滑动返回
self.webView.allowsBackForwardNavigationGestures = NO;
[self.webViewContent addSubview:self.webView];
htmlString = [@"<!DOCTYPE html><html xmlns=\"http:/" stringByAppendingString:@"/www.w3.org/1999/xhtml\"><head><title>WebMail-查看邮件内容</title></head><body style=\"font:14px/1.5 宋体,Arial,Verdana;\" >打开的邮件已使用"信息权限管理"进行保护,可以使用 Microsoft Office Outlook 2010 或 Outlook Web App 标准版打开。</body><html>"];
[self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"file:///"]];
}
模拟器截图,如下:
效果图.png
解决方案:
去掉htmlString中所有的 转义符;
网友评论