Search code examples
ioswebkitwkwebview

WKWebView+contentInset makes content size wrong


On iOS, when you set a contentInset on a WKWebView's scroll view, it seems to make the web view think the content of the page is bigger than it is. For example, if you give a mostly-empty page a top or bottom contentInset, you'll be able to scroll the page down even though there's nothing to scroll to.

Is this expected behavior? Is there a workaround that still allows me to use contentInset?


Solution

  • The problem is that WKWebView always seems to use its frame as its viewport size, neglecting to subtract the scrollView's contentInset. I was able to find a workaround by stephan-leroux.

    The idea is to set the WKWebView's frame to the desired viewport size, either manually or using autolayout constraints. To restore the "scroll-under" effect of contentInset, disable the scrollView's masksToBounds:

    wkWebview.scrollView.layer.masksToBounds = NO;