WKWebView加载HTML字体问题

2020-06-09  本文已影响0人  三岁就很乖

1、问题:后台给的HTML标签字符串用WKWebView加载时需要适当增大文字大小以及将文字两端对齐
解决办法:
文字增大
WKWebView代理方法中实现,使用js语句,文本两端对齐使用添加css样式实现
2、实现方法
代码1:

#pragma mark -webView delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //禁止用户选择
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.activeElement.blur();" completionHandler:nil];
    // 适当增大字体大小
    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '105%'" completionHandler:nil];
}

关键语句:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '105%'"

代码2:

displayContent = [NSString stringWithFormat:@"<div style=\"text-align:justify; text-justify:inter-ideograph;\">%@",displayContent];
[self.disPlayWeb loadHTMLString:displayContent baseURL:nil];

关键语句:<div style="text-align:justify; text-justify:inter-ideograph;"> 注:"在oc中需要转义为\"

补充
后台返回的带表情的文字完整示例:

<div style="text-align:justify; text-justify:inter-ideograph;"><p><span style="FONT-SIZE: 19px; FONT-FAMILY: &#39;Times New Roman&#39;,&#39;serif&#39;">Music is a part in our life, nearly everybody will listen to the music, no matter what nation they are from. Music is divided into many types. Once blues belonged to the black people, but as time went by, music is accepted by all classes. People always share the hottest songs together, just like they can communicate. Once in the foreign country, I had dinner in a restaurant, where there had the singers. People enjoyed the music when they were eating. At this moment, it was music that brought people together, and they share the same emotion.&nbsp;</span></p>

<div style="text-align:justify; text-justify:inter-ideograph;">为自己拼接的样式部分,用于两端对齐
3、WKWebView可配置最小字体
WKWebView 可以通过配置文件设置字体大小:

//创建网页配置对象
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 创建设置对象
WKPreferences *preference = [[WKPreferences alloc]init];
// 设置字体大小(最小的字体大小)
preference.minimumFontSize = 40;
// 设置偏好设置对象
config.preferences = preference;
// 创建WKWebView
WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.bounds  configuration:config];

4、WKWebView 加载 html 页面的时候,字体过于小的问题.
在 html 中添加以下代码:
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

设置页面的视口:适应屏幕宽度,初始缩放为1,最小缩放为1,最大缩放为1,用户不能缩放。
5、来自简书
https://www.jianshu.com/p/1502571dc231

上一篇 下一篇

猜你喜欢

热点阅读