思路如下:
- 在webview加载完之后添加一个contentSize的KVO
- 根据contentSize改变webView 高度约束
// 坚听高度变化
self.KVOController = [FBKVOController controllerWithObserver:self];
[self.KVOController observe:self.webView.scrollView keyPath:@"contentSize" options:NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
float height = selfWeak.webView.scrollView.contentSize.height;
NSLog(@"geight = %f",height);
[selfWeak changeLayoutByWebViewHeight:height];
}];
// 改变高度约束
- (void)changeLayoutByWebViewHeight:(float)height{
[self.webView mas_updateConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(height);
}];
}
遇到了一个问题~webView死循环, 高度越来越大直至crash
原因是:WKWebView 自动缩放导致webview.scrollerView.contentSize.height 一直大于webview.height
解决方案:禁用WKWebView的缩放功能
- (WKWebView *)webView{
if (!_webView) {
// 高度自适应js
NSString *sizejScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *sizeUScript = [[WKUserScript alloc] initWithSource:sizejScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// 禁止缩放
NSString *zoomingjScript = @" $('meta[name=description]').remove(); $('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );";
WKUserScript *zoomingUScript = [[WKUserScript alloc] initWithSource:zoomingjScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:sizeUScript];
[wkUController addUserScript:zoomingUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
_webView.backgroundColor = [UIColor redColor];//PCH_BANK_GRAY_ededed;//
_webView.scrollView.scrollEnabled = NO;
_webView.scrollView.layer.masksToBounds = NO;
_webView.scrollView.bounces = NO;
}
return _webView;
}