Force UIWebView to redraw?

2020-06-19 03:00发布

Are there any techniques to cause a UIWebView to redraw itself? I've tried setNeedsDisplay and setNeedsLayout on the UIWebView and its UIScrollView, but neither have worked.

2条回答
叼着烟拽天下
2楼-- · 2020-06-19 03:38

This save my life:

self.wkWebView.evaluateJavaScript("window.scrollBy(1, 1);window.scrollBy(-1, -1);", completionHandler: nil)

Add this line on webview did load delegate event or wkwebview did finish navigation

Thanks MAN!!!!

查看更多
Deceive 欺骗
3楼-- · 2020-06-19 03:47

Literally found the answer right after asking. The key was to tell the subviews of UIWebView's scrollView to redraw themselves - particularly the UIWebBrowserView.

- (void) forceRedrawInWebView:(UIWebView*)webView {
    NSArray *views = webView.scrollView.subviews;

    for(int i = 0; i<views.count; i++){
        UIView *view = views[i];

        //if([NSStringFromClass([view class]) isEqualToString:@"UIWebBrowserView"]){
            [view setNeedsDisplayInRect:webView.bounds]; // Webkit Repaint, usually fast
            [view setNeedsLayout]; // Webkit Relayout (slower than repaint)

            // Causes redraw & relayout of *entire* UIWebView, onscreen and off, usually intensive
            [view setNeedsDisplay]; 
            [view setNeedsLayout];
            // break; // glass in case of if statement (thanks Jake)
        //}
    }
}

I've commented out the if statement to be safe and avoid reliance on UIWebBrowserView's class name not changing. Without it, it hits all UIViews that are in the scrollview, which isn't really a problem at this point (no significant overhead incurred) but could always change.

EDIT:

In some cases, the following snippet of JavaScript will accomplish the same/similar thing:

window.scrollBy(1, 1); window.scrollBy(-1, -1);

You'd think UIScrollView's contentOffset would do this too, but that's not always the case in my experience - for some reason window.scrollTo is special in this regard.

Gist: https://gist.github.com/matt-curtis/5843862

查看更多
登录 后发表回答