天天看點

iOS計算UIWebView的高度和iOS8之後的WKWebView的高度問題

當我們涉及到webView和純代碼結合的時候,例如一個資訊詳情,其它位置想加上我們的純代碼控件,可以計算出webView的高度,然後放到scrollView上,然後在scrollView下邊或者什麼位置,加上自己的純代碼内容就行了.

下邊是計算UIWebView的高度:

第一種方法:

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

    float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

}

第二種方法:

- (void) webViewDidFinishLoad:(UIWebView *)webView

{

    CGRect frame = webView.frame;

    CGSize size = [webView sizeThatFits:CGSizeZero];

    frame.size = size;

    webView.frame = frame;

}

第三種方法:

- (void)viewDidLoad {

    [super viewDidLoad];

    webview.delegate = self;

    [webview loadHTMLString:@"<div id='foo' style='background: red'>fdasfda</div>" baseURL:nil];

}

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

    NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementByIdx_x_x_x("foo").offsetHeight;"];

    NSLog(@"height: %@", output);

}

下邊是計算WKWebView的高度:

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

{

    [_webViewevaluateJavaScript:@"document.body.offsetHeight"completionHandler:^(id_Nullable result,NSError * _Nullable error) {

        //擷取頁面高度,并重置webview的frame

        _webViewHeight = [resultdoubleValue];

        CGRect frame =webView.frame;

        frame.size.height =_webViewHeight;

        webView.frame = frame;

    }];

}

繼續閱讀