WKWebView加载HTML标签字体问题

今天在将UIWebView替换成WkWebView的过程中遇到一点小问题,就是加载后台由文本编辑器生成的HTML语言是字体大小出现了问题,显得很小,并且很紧凑。

后台给我们的标签字符串:

NSString *htmlContent = @"<body style='background-color:#fef5f3;margin:0.2rem 0;line-height:1rem;font-size:0.75rem;color:#61310a;padding: 0.5rem 0.8rem 0;'><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">优惠券领取规则</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">1、VIP优惠券每月可领,只能领取自身VIP等级相对应的优惠券;</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">2、优惠券请在有效期内使用,逾期自动失效;</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">3、退出VIP会员后,不再享受每月领券权益。</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">优惠券使用规则</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">1、只能使用对应等级的优惠券,使用后可获得相应奖励或减免;</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">2、优惠券限本人使用,不可转赠他人;</span></p><p style=\"white-space: normal; text-indent: 2em; text-align: justify; line-height: 1.5em;\"><span style=\"font-family: 微软雅黑, \" microsoft=\"\" font-size:=\"\">3、优惠券请在有效期内使用,逾期自动失效。</span></p><p><br/></p></body>";

WKWebView *webView = [[WKWebView alloc]  init];
//内容少于webView高度的时候不垂直滚动
 webView.scrollView.alwaysBounceVertical = NO;
//适配iOS 11 
[Toolkit setContentInsetAdjustmentBehaviorNever4ScrollView:webView.scrollView];
[webView loadHTMLString:htmlContent baseURL:nil];
[[NSURLCache sharedURLCache] removeAllCachedResponses];//删除web缓存
[self.view addSubview:self.topLine];
[self.view addSubview:self.webView];
self.webView = webView;
[self.view addSubview:self.progressView];
//获取标题和进度条
[self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];

之前UIWebView加载的情况:


UIWebView.png

还不错。

替换成WkWebView的展示:


WkWebView.png

绝对不能忍,字体变得太小了。

首先,出现这个问题的根本原因是标签中缺少meta标签,最简单的办法是让后台给我加上,将完整的标签格式返回给我们。但是,最简单的办法往往也是最难实现的,由于后台存储的是文本编辑器自动生成的标签语言,所以后台往往是从数据库中读取之后直接返回给我们了,我们的后台还不错,起码给我加了body标签,O(∩_∩)O哈哈~

啰嗦太多了,说一下解决方案吧,大体上有四种:

一、使用UIWebView

我&*#$%$%%,我换了干啥来着,当我没说。

一、拼接(上面第一种不算)

//我们在header标签里加上meta标签(大小关键是minimum-scale=1.1,数值越大,字体越大)
NSString *htmlHeader = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.1, user-scalable=no'></header>";
//
[htmlHeader stringByAppendingString:htmlContent];
[self.webView loadHTMLString:htmlContent baseURL:nil];

加载效果:


拼接效果.png

字体效果马马虎虎还可以,等等,怎么可以左右滚和上下滚了?我也不知道。未知的都是可怕的,方案pass掉。

二、在webView加载完毕的代理方法里通过调用JS方法改变

//代理
webView.navigationDelegate = self;
//MARK:-UINavigationDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //修改字体大小 240%
    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '240%'"completionHandler:nil];
    
    //修改字体颜色  #222222
    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#222222'"completionHandler:nil];
}

效果:


代理改变.png

字体变大了没错,颜色也改变了,不过这间距也太大了!!!而且网路慢的话还有字体本来小,加载完成变大的问题。
就当熟悉一下evaluateJavaScript方法了,改变颜色还是可以滴,再次pass。

三、通过WKUserScript注入JavaScript脚本和WKPreferences设置字体大小

//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;
//改变初始化方法
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];

效果:


WKWebView脚本注入.png

效果不错,跟UIWebView加载效果一样,提上裤子走人!

忘了说字体设置了。。。。。。。。。(不脱了!就一会儿)

// 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        // 设置字体大小(最小的字体大小)
        preference.minimumFontSize = 15;
        // 设置偏好设置对象
        wkWebConfig.preferences = preference;

效果:


字体设置.png

满足了。。。

我的代码:

#import "RequestHTMLViewController.h"
#import <WebKit/WebKit.h>

@interface RequestHTMLViewController ()

@property(nonatomic, strong) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;//进度条
@property (nonatomic,strong) UIView *topLine;

@end

@implementation RequestHTMLViewController

//MARK:-lazy load
-(UIView *)topLine{
    if (!_topLine) {
        UIView *lineV = [UIView new];
        lineV.backgroundColor = [Toolkit getColor:hex_cccccc];
        _topLine = lineV;
    }
    return _topLine;
}

- (UIProgressView *)progressView
{
    if(!_progressView)
    {
        UIProgressView *progressV = [UIProgressView new];
        progressV.tintColor = [Toolkit getColor:hex_red_color];
        progressV.trackTintColor = [UIColor whiteColor];
        _progressView = progressV;
    }
    return _progressView;
}

-(WKWebView *)webView{
    if (!_webView) {
        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;

        // 创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];
        // 设置字体大小(最小的字体大小)
        preference.minimumFontSize = 15;
        // 设置偏好设置对象
        wkWebConfig.preferences = preference;
        
        
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        webView.scrollView.alwaysBounceVertical = NO;
        [Toolkit setContentInsetAdjustmentBehaviorNever4ScrollView:webView.scrollView];
        _webView = webView;
    }
    return _webView;
}

//MARK:-lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _topView.backgroundColor = [Toolkit getColor:hex_red_color];
    _lblTitle.text = self.requestTitle;
    _lblTitle.textColor = [UIColor whiteColor];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];//删除web缓存
    [self.view addSubview:self.topLine];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    //获取标题和进度条
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    [self makeMasConstraints];
}

-(void)dealloc{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];//删除web缓存
    
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

//MARK:-setter
-(void)setRequestService:(NSString *)requestService{
    _requestService = requestService;
    [self contentRequest];
}


//MARK:-request
-(void)contentRequest{
    if (self.requestService) {
        NSDictionary *params = @{ServiceKey:self.requestService};
        [[Mall_APIManager sharedManager] JQ_common_requestWithParams:params andBlock:^(id data, NSError *error) {
            //        NSLog(@"data ====== %@",data);
            NSNumber * ret=data[@"ret"];
            if ([ret isEqualToNumber:kRequestSuccess]) {
                //            NSDictionary *contentDic = data[@"data"][@"content"];
                NSString *htmlContent = data[@"data"][@"content"];
                [self.webView loadHTMLString:htmlContent baseURL:nil];
            }else if ([ret isEqualToNumber:kRequestError]){
                [SVProgressHUD showInfoWithStatus:data[@"msg"]];
            }
        }];
    }
}

//MARK:-kvo监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"title"] && (object == self.webView)) {
        
        _lblTitle.text = self.webView.title;
        
    } else if ([keyPath isEqual: @"estimatedProgress"] && object == self.webView) {
        
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if(self.webView.estimatedProgress >= 1.0f) {
            
            [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
            
        }
    } else {
        
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark -  makeMasConstraints
- (void)makeMasConstraints {
    [self.topLine makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topView.mas_bottom);
        make.height.equalTo(@0.5);
        make.left.width.equalTo(_topView);
    }];
    
    [self.progressView makeConstraints:^(MASConstraintMaker* make){
        make.top.equalTo(self.topLine.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.equalTo(@1.5);
        
    }];
    [self.webView makeConstraints:^(MASConstraintMaker* make){
        make.top.equalTo(self.topLine.bottom);
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        
    }];
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容