Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force UIWebView to redraw?

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.

like image 928
mattsven Avatar asked Jun 23 '13 04:06

mattsven


1 Answers

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

like image 93
mattsven Avatar answered Oct 30 '22 07:10

mattsven