WKWebView加载 html 页面内容自适应

常常在项目中会遇到要用 WKWebView 加载一段后台由文本编辑器生成的 HTMLString 。因为无法控制页面内容,有时候默认显示的时候会出现文字很小很紧凑、图片太宽超出屏幕等问题,非常不美观,在此提供两种方法解决。

方法一:

//通过WKUserScript注入JavaScript脚本和WKPreferences设置字体大小
WKPreferences * preference = [[WKPreferences alloc] init];
preference.javaScriptCanOpenWindowsAutomatically = YES;

//图片自适应宽高
NSString * jSString = @"var objs = document.getElementsByTagName('img');for(var i=0;i++){var img = objs[i];img.style.maxWidth = '100%';img.style.height='auto';}";
WKUserScript * wkUScript1 = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//文字修改大小
NSString * jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript * wkUScript2 = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

WKUserContentController * wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript1];
[wkUController addUserScript:wkUScript2];
//配置对象
WKWebViewConfiguration * wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
wkWebConfig.preferences = preference;

self.webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];

使用的时候调用方法即可:
[self.webView loadHTMLString:contentString baseURL:nil];
这种方法有时候使用并不能解决问题,还未找到原因,若有大神了解,还请指导一下,感谢!
个人比较推荐第二种方法,亲测可用,自己项目中用的也是方法二。

方法二:

//HTML适配图片文字
- (NSString *)adaptWebViewForHtml:(NSString *) htmlStr {
    NSMutableString *headHtml = [[NSMutableString alloc] initWithCapacity:0];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"" ];
    //适配图片宽度,让图片宽度等于屏幕宽度
    //[headHtml appendString : @"" ];
    //[headHtml appendString : @"" ];
    //适配图片宽度,让图片宽度最大等于屏幕宽度
//    [headHtml appendString : @""];
    //适配图片宽度,如果图片宽度超过手机屏幕宽度,就让图片宽度等于手机屏幕宽度,高度自适应,如果图片宽度小于屏幕宽度,就显示图片大小
    [headHtml appendString : @"\n"];
    [headHtml appendString : @"" ];
    [headHtml appendString : @"webview" ];
    NSString *bodyHtml;
    bodyHtml = [NSString stringWithString:headHtml];
    bodyHtml = [bodyHtml stringByAppendingString:htmlStr];
    return bodyHtml;
}

使用的时候调用方法即可:
[self.webView loadHTMLString:[self adaptWebViewForHtml:contentString] baseURL:nil];

如果你有更好的方法,请留下脚印,欢迎大家一起讨论、一起变优秀❤️
若能帮助到你,请打一颗小星星哦~~

你可能感兴趣的:(WKWebView加载 html 页面内容自适应)