问题
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!
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/45994641/calculate-uiwebview-content-dynamic-height-using-document-body-scrollheight-r