iOS WKWebView 加载富文本图片适配
2021-06-11 本文已影响0人
selice
NSString *htmls = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-size:15px;}\n"
"</style> \n"
"</head> \n"
"<body>"
"<script type='text/javascript'>"
"window.onload = function(){\n"
"var $img = document.getElementsByTagName('img');\n"
"for(var p in $img){\n"
" $img[p].style.width = '100%%';\n"
"$img[p].style.height ='auto'\n"
"}\n"
"}"
"</script>%@"
"</body>"
"</html>",htmlString];
[self.webView loadHTMLString:htmls baseURL:nil];
下面是适配内容方法
NSString *injectionJSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content','width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *injectionJSStringScript = [[WKUserScript alloc] initWithSource:injectionJSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
NSMutableString *javascript = [NSMutableString string];
[javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
[javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *userController = [WKUserContentController new];
[userController addUserScript:injectionJSStringScript];
[userController addUserScript:noneSelectScript];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.preferences = [WKPreferences new];
config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.userContentController = userController;
self.wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0,AP_ScreenWidth, 3000) configuration:config];
self.wkWebView.scrollView.scrollEnabled = NO;
self.wkWebView.scrollView.bounces = NO;
self.wkWebView.userInteractionEnabled = NO;
if (@available(iOS 11.0, *)) {
self.wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
self.wkWebView.navigationDelegate = self;
self.wkWebView.scrollView.delegate = self;
//监听wekwebview 的高度来获取webview高度
// [self.wkWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
[self addSubview:self.wkWebView];