Search code examples
iosuiwebviewuiscrollviewnslayoutconstraintcontentoffset

UIWebView apparently scrolled after loading content from URL


I am loading an HTML document into a UIWebView with loadRequest:requestURL. The HTML content does not fit entirely into the view's frame. What surprises me that at the time the page has been loaded (when webViewDidFinishLoad:is called) the view's scrollView.contentOffset is different from (0,0). It looks as if the content may have been scrolled down approximately so that its vertical center is aligned with the view's vertical center (see screenshot below).

How can this happen and how can I achieve the desired behavior of having the content's top left corner aligned with the view's top left corner initially? Setting scrollView.contentOffset to (0,0) in webViewDidFinishLoad:` is an option but apparently leads to some flickering.

This is occurring in the context of a UIViewController that contains two sibling UIWebViews below its root view. The two UIWebViews are vertically stacked with a UILabel (appears in screenshot with gray background) in between. (The lower UIWebView is not visible in the screenshot, because it's currently all white.) The view uses constraint-based layout and the current problem concerns the upper UIWebView.

UPDATE Further study has revealed that the visual defect is not due to scrolling in the upper UIWebView but due to its frame.origin.y having been set from 0 to 64 (which is also the combined height of the status bar and the navigation bar) by the time webViewDidFinishLoad is called. I am calling loadRequest:requestWithURL: from the view controller's viewWillAppear: and there is a layout constraint on the upper UIWebView that imposes a vertical space of 0 between its top and the bottom of the Top Layout Guide.

enter image description here


Solution

  • I think what happens is the following: iOS 7 wants UIScrollViews to extend underneath the status and navigation bars when scrolled downwards. Apparently it performs the initial vertical scrolling as a means for preventing the top part of web content from being hidden behind these bars before any scrolling occurs.

    I had a layout constraint for a vertical distance of 0 to the top layout guide placed on the UIWebView which led to the wrong vertical distance of twice the height of the status bar plus the height navigation bar from the top of the screen. Replacing this layout constraint by one for a vertical distance of 0 from the superview corrected the wrong.