首页 > 系统 > iOS > 正文

iOS WKWebView高度自适应以及截获页面点击的url

2019-11-08 00:21:26
字体:
来源:转载
供稿:网友

首先来看下UIWebView的做法:

UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,0,WIDTH,0)];

webView.delegate =self;

[self.viewaddSubview:webView];

[webView loaDHTMLString:html/*html内容*/ baseURL:nil];

-(void)webViewDidFinishLoad:(UIWebView*) webView {

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

    CGFloat documentHeight = [[webViewstringByEvaluatingjavaScriptFromString:@"document.getElementById(/"content/").offsetHeight;"]floatValue];

    CGRect frame = webView.frame;

    frame.size.height = documentHeight;

    webView.frame = frame;

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    

    NSString* strRequest = request.URL.absoluteString;

    

    if([strRequestisEqualToString:@"about:blank"]) {//主页面加载内容

        returnYES;//允许跳转

    } else {//截获页面里面的链接点击

        //do something you want

        returnNO;//不允许跳转

    }

}

在来对应看下WKWebView:

WKWebView   *wkWebview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 0)];

wkWebview.navigationDelegate = self;

[self.view wkWebview];

[wkWebview loadHTMLString:html/*html内容*/ baseURL:nil];

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecifiedWKNavigation *)navigation {

    [webView evaluateJavascript:@"document.getElementById(/"content/").offsetHeight;"completionHandler:^(id_Nullableresult,NSError *_Nullable error) {

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

        CGFloat documentHeight = [resultdoubleValue];

        CGRect frame = webView.frame;

        frame.size.height = documentHeight;

        webView.frame = frame;

    }];

}

// 类似 UIWebView的 -webView: shouldStartLoadWithRequest: navigationType:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    

    NSString *strRequest = [navigationAction.request.URL.absoluteStringstringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    if([strRequestisEqualToString:@"about:blank"]) {//主页面加载内容

        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转

    } else {//截获页面里面的链接点击

        //do something you want

decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转

    }

}

高度自适应代码下载链接:http://download.csdn.net/detail/luco2008/9502733
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表