【问题标题】:How to calculate the height of a WKWebView? [duplicate]如何计算 WKWebView 的高度? [复制]
【发布时间】:2016-10-20 01:12:35
【问题描述】:

我想在我的项目中这样计算WKWebView的高度,但是总是没有用,我怎么得到它?

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation     *)navigation{
    [webView sizeToFit];
    _height = webView.frame.size.height ;
}

【问题讨论】:

  • 这个方法是否调用?
  • 是的,它返回一个高度但不精确。

标签: ios objective-c wkwebview


【解决方案1】:

你可以使用 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);
}
}

这将节省 JavaScript 的使用并让您随时了解所有更改。

【讨论】:

  • 很抱歉这么晚才回复你,我在朋友的帮助下解决了这个问题。非常感谢。
  • 如果你解决了,你能发布解决方案吗?
【解决方案2】:

我尝试了滚动视图 KVO,并尝试评估文档上的 javascript,使用 clientHeightoffsetHeight 等内容...

最终对我有用的是:document.body.scrollHeight。或者使用最顶层元素的scrollHeight,例如一个容器div

我使用 KVO 监听 loading WKWebview 属性更改,当它完成加载时,我确定高度如下:

[self.webview evaluateJavaScript: @"document.body.scrollHeight"
                       completionHandler: ^(id response, NSError *error) {
            NSLog(@"Document height: %@", response);
}];

【讨论】:

    【解决方案3】:

    UIView 的边界是矩形,表示为相对于其自身坐标系 (0,0) 的位置 (x,y) 和大小 (width,height)。 UIView 的 frame 是一个矩形,表示为相对于它所在的 superview 的位置 (x,y) 和大小 (width,height)。

    因此,我认为您只需要定位 bounds.height 而不是它的框架。

    【讨论】:

    • 很抱歉这么晚才回复你,我在朋友的帮助下解决了这个问题。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 2017-06-28
    • 2019-06-26
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多