美文网首页iOS程序员的业余沙龙
WKWebView高度精准自适应

WKWebView高度精准自适应

作者: 東玖零 | 来源:发表于2017-10-29 02:46 被阅读983次

原理:利用WKWebView 有提前注入一段js方法,在页面加载完成后调用此方法并获取返回值的能力。

前提:需要在html的body的最后加一个空标签,id为myid。

1.注入js代码(包含一个refreshView方法)

let js = "function refreshView () {" +
        "var imgstyle=document.getElementsByTagName('img');" +
        "for(var i=0;i<imgstyle.length;i++){" +
            "imgstyle[i].style.width='\(k_screen_width)'+'px';" +
            "imgstyle[i].style.height = 'auto';" +
        "}" +
        "return document.getElementById('myid').offsetTop;}"

2.拼接html并加载

let header = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta  name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><link rel=\"stylesheet\" type=\"text/css\" /><style type=\"text/css\"> </style></head>"
let div = "<div id='myid' style = 'width:100%;height:10px;background-color:green;display:block'></div>"
let html = "<html>" + header + "<body style='width:100%;background-color:red;padding:0px;margin:0px;display:block;'>" + body + div + "</body></html>"
self.wkWebView.loadHTMLString(html, baseURL: nil)

3.在加载完成后调用refreshView方法

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("refreshView()") {[weak self] (obj, error) in
//            DLog(items: "-------obj = \(String(describing:obj)),error = \(String(describing: error))")
            if let hasSelf = self {
                hasSelf.evaluateJavaScript(obj: obj, error: error)
            }
        }
    }
    
    func evaluateJavaScript(obj:Any?, error:Error?) {
        if let height = obj as? CGFloat {
//            DLog(items: "height----\(height)")
            if height != self.height {
                self.frame = CGRect(x: 0, y: 0, width: k_screen_width, height: height)
                self.wkWebView.frame = self.bounds
                if let block = self.refresh {
                    block()
                }
            }
        }
    }
头部.png 中部.png 底部.png

相关文章

网友评论

  • 人世间1207:楼主能给个demo吗?
  • 何年何月:不错不错
  • 黄花菜先生:来个oc版本
    東玖零:- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    __weak typeof(self) weakSelf = self;
    [webView evaluateJavaScript:@"refreshView()" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
    [weakSelf evaluateJavaScript:obj error:error];
    }];
    }

    - (void)evaluateJavaScript:(id)obj error:(NSError *)error {
    NSNumber *height = obj;
    NSLog(@"%@",height);
    }
    東玖零:NSString *header = @"<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><link rel=\"stylesheet\" type=\"text/css\" /><style type=\"text/css\"> </style></head>";
    NSString *div = @"<div id='myid' style = 'width:100%;height:10px;background-color:green;display:block'></div>";
    NSString *html = [NSString stringWithFormat:@"<html>%@<body style='width:%@;background-color:red;padding:0px;margin:0px;display:block;'>%@%@</body></html>",header,@"100%",body,div];
    WKUserScript *sc = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *user = [[WKUserContentController alloc] init];
    [user addUserScript:sc];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config setUserContentController:user];
    WKWebView *wkweb = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [wkweb setUIDelegate:self];
    [wkweb setNavigationDelegate:self];
    [self.view addSubview:wkweb];
    [wkweb loadHTMLString:html baseURL:nil];
    東玖零:NSString *body = @"<img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t12676/112/2121410133/351737/a1e2ef42/5a424fa1N39408dea.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t12313/78/2581289049/342715/22817ce7/5a424f86Ndcd54ab9.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t15577/327/932025178/337478/367a0e92/5a424fa3N7fae30eb.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t16054/190/763100472/277599/ec143e5a/5a424fb1Nfa7ec3c1.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t13477/284/2497192791/314947/6e4afe91/5a424fbbNfdd82ab4.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t14203/110/1049807750/400254/5e145b10/5a424fc3N46d9a2f0.jpg\"><img src=\"https://img30.360buyimg.com/popWareDetail/jfs/t12784/257/2566146156/405267/628ad411/5a424fb9N1c664370.jpg\">";
    int k_screen_width = self.view.frame.size.width;
    NSString *js = [NSString stringWithFormat:@"function refreshView() {\
    var imgstyle=document.getElementsByTagName('img');\
    for(var i=0;i<imgstyle.length;i++){\
    imgstyle[i].style.width='\%d'+'px';\
    imgstyle[i].style.height = 'auto';\
    }\
    return document.getElementById('myid').offsetTop;\
    }",k_screen_width];

本文标题:WKWebView高度精准自适应

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