Calculate UIWebView Content dynamic Height using &

2019-06-17 05:26发布

I am creating on an application using Objective C, where I'm using a UIWebView to display contents in HTML format. I am using below code in UIWebView delegate method webViewDidFinishLoad

NSUInteger contentHeight = [[aWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollHeight;"]] intValue];

to calculate the webview content height, this is working fine in iOS8, iOS9 and iOS11 but in iOS10 iPhone mobiles the content height returning a much bigger value than the actual content value. Because of this, I am getting some extra white space in bottom of my webview in screen.

I tried all the solutions but getting the same wrong content height only in iOS 10. Please help me to resolve this problem. Thank You in Advance!

3条回答
神经病院院长
2楼-- · 2019-06-17 05:55

I've struggled quite a lot to resize WebView correctly.

Try to add one more step before evaluating document.body.scrollHeight.

Something like this:

-(void) webViewDidFinishLoad:(UIWebView *)webView {
    if[[webView stringByEvaluatingJavaScriptFromString:@"document.readyState"] isEqualToString:@"complete"]){
webViewHeight = [[WebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
//resize logic
}

I'm writing my code in swift and for WKWebView, but it's the same thing basically. The point is to catch scrollHeight (or offsetHeight - couldn't figure out the difference in this case) at the right moment, and it seems that that moment is only after document.readyState.

Hope this will help you.

查看更多
小情绪 Triste *
3楼-- · 2019-06-17 06:08

Sadly, I can't track down the issue either. BUT, I think i know the culprit: html <tables> and auto-resize. There is a fair bit of discussion, in apple's safari changelog, about viewport and rendering changes, but nothing specific enough.

It would appear webviews (safari powered) render HTML differently between versions; makes sense, though i can't distill much rhyme or reason and explicit css for the <table> and <body> yielded nothing.

Hopefully, this partial answer helps make some progress or at least a work around.

查看更多
男人必须洒脱
4楼-- · 2019-06-17 06:09

I had used following way to get contentSize.

i have added observer(KVO) on webview's scrollview.

self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil);

Now, whenever contentsize of webview will get changed, i get callback in this method

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
}

Now take the contentSize of object from this method and use that.

查看更多
登录 后发表回答