美文网首页
使用WKWebView自适应屏幕遇到的问题以及最后解决的方法

使用WKWebView自适应屏幕遇到的问题以及最后解决的方法

作者: Ink_lhe | 来源:发表于2017-04-11 10:54 被阅读0次

在网上找了很多方法我就不废话了 先一一列举出来
第一种方法:这种方法适配屏幕不是太好,双击才可以完全适配屏幕,有兴趣的话可以自己试一下

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [RYLoadingView hideRequestLoadingView];
    NSString *inHtmlStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
                           "script.type = 'text/javascript';"
                           "script.text = \"function ResizeImages() { "
                           "var myimg,oldwidth;"
                           "var maxwidth = %f;" // UIWebView中显示的图片宽度
                           "for(i=0;i <document.images.length;i++){"
                           "myimg = document.images[i];"
                           "if(myimg.width > maxwidth){"
                           "oldwidth = myimg.width;"
                           "myimg.width = maxwidth;"
                           "}"
                           "}"
                           "}\";"
                           "document.getElementsByTagName('head')[0].appendChild(script);",MainScreenWidth-20];
    [webView evaluateJavaScript:inHtmlStr completionHandler:^(id item, NSError * _Nullable error) {
        // Block中处理是否通过了或者执行JS错误的代码
        // 如果要获取web高度必须在网页加载完成之后获取
        CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
        NSLog(@"加载web完成\n网页高度:  %@",NSStringFromCGSize(fittingSize));
        _webView.frame = CGRectMake(10, 10, MainScreenWidth-20, fittingSize.height);
        // 用通知发送加载完成后的高度
        webViewHeight = fittingSize.height;
        if (curSegType == 0) {
            [_secScrollView setContentSize:CGSizeMake(MainScreenWidth, webViewHeight)];
        }
    }];
}

第二种方法:

在初始化WKWebView的时候添加配置可以解决自适应的问题 ,但是在加载的内容宽度大于高度的时候就有些不准确了,宽度无法自适应屏幕的宽度,最后我也没搞明白是因为什么原因,最后就放弃了这个方法。


Paste_Image.png

//自适应屏幕宽度js


NSString*jSString = [NSStringstringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content','width=device-width','user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);"];

WKUserScript*wkUserScript = [[WKUserScriptalloc]initWithSource:jSStringinjectionTime:WKUserScriptInjectionTimeAtDocumentEndforMainFrameOnly:YES];

//添加自适应屏幕宽度js调用的方法

WKUserContentController* userContent = [[WKUserContentControlleralloc]init];

[userContentaddUserScript:wkUserScript];

wkWebConfig.userContentController= userContent;

self.webView= [[WKWebViewalloc]initWithFrame:CGRectMake(10,10,MainScreenWidth-20,webViewHeight)configuration:wkWebConfig];

//监听加载进度

[self.webViewaddObserver:selfforKeyPath:@"loading"options:NSKeyValueObservingOptionNewcontext:NULL];

在加载的过程中我使用KVO监听加载的进度,从而获取最后加载内容的高度。

根据WKWebView的状态去判断是否加载完成:

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {

WKWebView*webView = object;

if(webView.loading){

NSLog(@"加载中");

}

if(!webView.loading) {

//获取页面高度,并重置webview的frame

webViewHeight= webView.scrollView.contentSize.height;

CGRectframe = webView.frame;

if(webViewHeight<=0) {

webViewHeight=MainScreenHeight-BottomH-TopTabBarH-64;

}

frame.size.height=webViewHeight;

_webView.frame= frame;

if(curSegType==0) {

[_secScrollViewsetContentSize:CGSizeMake(MainScreenWidth,webViewHeight)];

}

}

}

有可能需要用到进度条和title属性

[webView addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNew context:NULL];

[webView addObserver:selfforKeyPath:@"title"options:NSKeyValueObservingOptionNew context:NULL];

一定一定要记得移除KVO监听

#pragma mark - 移除KVO
- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:@"title"];
    [_webView removeObserver:self forKeyPath:@"goBack"];
    [_webView removeObserver:self forKeyPath:@"goForward"];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];

}

第三种方法 也是我最后使用的方法:
我的需求是让图片的大小跟着屏幕的变化而变化,就是动态的去适应屏幕;那么文字的字体就是自己可以控制,可大可小。要想达到这样的效果,在用loadHTMLString加载字符串之前对它进行处理

 NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                               "<head> \n"
                               "<style type=\"text/css\"> \n"
                               "body {font-size:14px;}\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>",curObj.content];
            [_webView loadHTMLString:htmls baseURL:nil];

处理HTMLString的原理:
原理就是用一个for循环,拿到所有的图片,对每个图片都处理一次,让图片的宽为100%,就是按照屏幕宽度自适应;让图片的高atuo,自动适应。文字的字体大小,可以去改font-size:14px

相关文章

网友评论

      本文标题:使用WKWebView自适应屏幕遇到的问题以及最后解决的方法

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