Load web page so it displays from top of the page initially


Forgive me if the answer to my question is covered in the very next chapter, but when I click on an item in the table view and the web page loads in the UIWebView, the web page scrolls all the way to the bottom. Yuck!

I know that the web view is embedded in a UIScrollView, and I guessed that UIWebView has a delegate; so I set up this method in WebViewController, after making it the delegate of its view:

- (void)webViewDidFinishLoad:(UIWebView *)webView { [[webView scrollView] setContentOffset:CGPointZero animated:NO]; }

This more or less works the way I want it to—the page loads at the top. However, there is this nasty flash when the page loads. I’m guessing that the page loads and scrolls all the way to the bottom (as it does without my method) and then immediately jumps to the top, causing the apparent flash to the user. I tried putting this functionality in webViewDidStartLoad:, but that has no effect. It seems like the page needs to finish loading before you can reposition it in the scroll view.

Is there a prettier way of handling this? My guess is that there is a way of loading the page “offscreen” and then putting it in the scroll view with the desired offset—something like that anyway. Maybe there’s a better way of doing it. Any ideas? Thanks!


Try setScalesPageToFit?


The “problem” is not with the WebView, it is the link returned with the RSS feed. All the links contain an internal anchor reference at the end “#pXXXX” so the browser jumps to the top of the correct post. Remove that and it will display the top of the page.


Thanks! I never even considered the possibility of an anchor tag. That’s something to look out for.


I ended up removing my original fix, where I fudge the contentOffset (see above), and built the URL with a custom method that removes the fragment:

- (NSURL *)urlFromString:(NSString *)urlString removeFragment:(BOOL)remove
    NSURL *url = [NSURL URLWithString:urlString];
    if (remove == NO || ![url fragment]) {
        return url;
    else {
        // As of 2013.02.15, a URL for an entry ends along the lines of this:
        // viewtopic.php?f=237&t=5660&p=16092#p16092
        NSString *fragment = [NSString stringWithFormat:@"#%@", [url fragment]];
        return [NSURL URLWithString:[urlString stringByReplacingOccurrencesOfString:fragment withString:@""]];