background
In the process of iOS development, when we need to modify the font size of the WebView, we need to set and update the frame of the WebView. At this time, we will encounter a common problem, that is, when the font changes from small to large, it is normal. When the font changes from large to small, The height of the Webview does not change, which leads to a large blank space at the bottom of the Webview. After many explorations and inquiries, I finally found the root of the problem.
knowledge
To understand this, you need to know the following about HTML:
1.body
The label
Once the height of the body tag is set, if the content inside the tag is higher than the height of the body, the body will be stretched and the height will change. Otherwise, the size of the body will not change and the height will be fixed.
2. Set the font size
document.getElementsByTagName('body') [0].style.webkitTextSizeAdjust= 100%
Copy the code
3. Get the body height
document.body.offsetHeight
Copy the code
Code implementation
1. Incorrect acquisitionwebview
Content height method
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
__weak typeof(self) weakSelf = self;
[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable m, NSError * _Nullable error) {
CGFloat webHeight = [m floatValue];
webView.frame = CGRectMake(KAdapter(5), 0, kScreenWidth, webHeight);
}];
}
Copy the code
2. Correct acquisitionwebview
Content height approach
Apply another layer inside the body tag, as follows:
<body><div id='bodybox'></div></body>
Then get the height of the div:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
__weak typeof(self) weakSelf = self;
[webView evaluateJavaScript:@"document.getElementById('bodybox').offsetHeight" completionHandler:^(id _Nullable m, NSError * _Nullable error) {
CGFloat webHeight = [m floatValue];
webView.frame = CGRectMake(0.0, kScreenWidth, webHeight);
}];
}
Copy the code
If you follow this method, you will get the correct height of the WebView, regardless of whether the font size is from large to small or from small to large.