美文网首页ios 知识点iOS之webView与JS交互篇
WKWebView加载HTML标签字体问题

WKWebView加载HTML标签字体问题

作者: crazy一笑 | 来源:发表于2018-05-16 16:03 被阅读455次

    今天在将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);
            
        }];
        
    }
    

    相关文章

      网友评论

        本文标题:WKWebView加载HTML标签字体问题

        本文链接:https://www.haomeiwen.com/subject/acipdftx.html