iOS UIWebView加载,获取WebView实际高度

需求:一个底部UIScrollView,上面是一个UIImageView,下面是一个UIWebView,要求加载完UIWebView,禁止UIWebView滚动,UIWebView全部显示,如果大于屏幕高度,UIScrollView滚动,否则不滚动

根据需求需要获取UIWebView的实际高度,以便设置UIScrollView的contentSize

1加载webView

@property (nonatomic,strong) UIWebView *webView;
-(UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectZero];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}

2 当WebView加载完成后,禁止WebView滚动

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    webView.scrollView.scrollEnabled = NO;
}

3 KVO监听webView的contentSize变化,拿到实际高度,重置约束,设置UIScrollView的contentSize

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {
        
        CGPoint point = [change[@"new"] CGPointValue];
        
        CGFloat height = point.y;
        NSLog(@"point.y---%f",height);
        
        CGSize fittingSize = [_webView sizeThatFits:CGSizeZero];
        
        CGFloat webHeight = fittingSize.height;

        [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(webHeight);
        }];
        self.bgScrollView.contentSize = CGSizeMake(self.view.ssWidth, self.topView.ssHeight+webHeight);
    }
}

大功告成,另外说一下为什么不在webViewDidFinishLoad中直接获取webView高度,因为如果webView中加载的有图片,如果图片显示慢了,就可能在webViewDidFinishLoad中拿不到图片高度,这样拿到的高度有可能偏低,所以我这里通过KVO拿webView高度,而不是在webViewDidFinishLoad中直接获取

你可能感兴趣的:(iOS UIWebView加载,获取WebView实际高度)