美文网首页
获取WKWebView高度

获取WKWebView高度

作者: 强子ly | 来源:发表于2020-07-06 19:07 被阅读0次

    目录

    • 通过代理执行JS方法获取
    • 通过KVO获取

    方法一:通过代理执行JS方法获取
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
        [webView evaluateJavaScript:@"document.body.scrollHeight"
                  completionHandler:^(id _Nullable result,NSError *_Nullable error) {
            // 高度
            CGFloat scrollViewHeight = [result doubleValue];
        }];
    }
    
    方法二:通过KVO获取
    // 添加KVO监听
    [_webView.scrollView addObserver:self
                          forKeyPath:@"contentSize"
                             options:NSKeyValueObservingOptionNew
                             context:nil];
    
    // 实现监听方法
    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                           context:(void *)context {
        UIScrollView *scrollView = object;
        NSLog(@"%@", @(scrollView.contentSize.height));
    }
    
    // 移除监听
    - (void)dealloc{
        [self.webView.scrollView removeObserver:self
                                     forKeyPath:@"contentSize"];
    }
    

    相关文章

      网友评论

          本文标题:获取WKWebView高度

          本文链接:https://www.haomeiwen.com/subject/llpgqktx.html