ios - Why does the content displayed sometimes differ when loading the same html text using WKWebView?
阿神
阿神 2017-07-06 10:35:34
0
1
2325

As shown:

The red box part is WKWebView, the one on the left is normal display, and the one on the right is abnormal display.
I executed the webview highly adaptive content in the callback when the webpage is loaded:

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    if ([webView isFinishLoading] == YES) {
        self.webView.height = self.webView.scrollView.contentSize.height;

The heights obtained on the left and right sides are the same, but the right side is not fully displayed and is also enlarged.

What confuses me the most is that sometimes the loading is complete and sometimes it is incomplete.

What makes me even more confused is that if I write a delayed load to delay it for one second, the display at this time will be correct:

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    if ([webView isFinishLoading] == YES) {
        
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 1秒后异步执行这里的代码...
            
            weakSelf.webView.height = weakSelf.webView.scrollView.contentSize.height;

If I use UIWebView instead of WKWebView, I won't encounter this problem.

Who can tell me why the page is sometimes not fully displayed. . . Thank you in advance

阿神
阿神

闭关修行中......

reply all(1)
代言

I have also encountered this situation, and occasionally the page content is not fully displayed. Later I found that didFinishNavigation was sometimes called multiple times, and the first time webView.scrollView.contentSize was printed as (width = 0, height =0). So after isFinishLoading , directly setting webView.height will result in incomplete content.
Solution:
judge webView.scrollView.contentSize.height to be non-0, and then set webView.height; or use KVO to monitor the value changes of webView.scrollView.contentSize. Both are available.


Judge height

if (!self.webView.isLoading) {
    if(webView.scrollView.contentSize.height > 0)
    {
        self.webView.height = self.webView.scrollView.contentSize.height;
        [self.webView sizeToFit];
    }
}

KVO monitor contentSize

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (!self.webView.isLoading) {
        if([keyPath isEqualToString:@"scrollView.contentSize"])
        {
            webView.height = webView.scrollView.contentSize.height;
            [webView sizeToFit];
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template