0

I want to calculate the height of a WKWebView in my project like this, but it always no use, how can I get it?

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation     *)navigation{
    [webView sizeToFit];
    _height = webView.frame.size.height ;
}
Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
charels
  • 11
  • 1
  • 5

3 Answers3

1

You could use Key value Observing

 - (void)viewDidLoad {
...
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}


- (void)dealloc
{
[self.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}


- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context
{
if (object == self.webView.scrollView && [keyPath isEqual:@"contentSize"]) {
    // we are here because the contentSize of the WebView's scrollview changed.

    UIScrollView *scrollView = self.webView.scrollView;
    NSLog(@"New contentSize: %f x %f", scrollView.contentSize.width, scrollView.contentSize.height);
}
}

This would save the use of JavaScript and keep you in the loop on all changes.

HariKrishnan.P
  • 1,204
  • 13
  • 23
1

I've tried the scroll view KVO and I've tried evaluating javascript on the document, using things like clientHeight, offsetHeight, etc...

What worked for me eventually is: document.body.scrollHeight. Or use the scrollHeight of your top most element, e.g. a container div.

I listen to the loading WKWebview property changes using KVO and when it's done loading I determine the height like so:

[self.webview evaluateJavaScript: @"document.body.scrollHeight"
                       completionHandler: ^(id response, NSError *error) {
            NSLog(@"Document height: %@", response);
}];
natanavra
  • 2,100
  • 3
  • 18
  • 24
0

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0). The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

Hence, I think you simply need to target the bounds.height instead of its frame.

  • I am so sorry for reply you so late,I solved this problem with the help of my friend.Thank you very much. – charels Jun 21 '16 at 03:14