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
?
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;
weiyin's suggestion (resizing the web view's frame) worked for me.
Just wanted to share a code example:
CGFloat topInset = ...;
web.scrollView.layer.masksToBounds = NO;
[web.scrollView setContentInset:UIEdgeInsetsMake(topInset, 0, 0, 0)];
[web setFrame:CGRectMake(0, 0, web.width, web.height-topInset)];
Four years later and the problem still persists...
weiyin's answer works great, but if you're like me you might struggle a bit with figuring out what exactly to do (though it's really quite simple).
Embed your Web View inside a Wrapper View.
Size and position your Web View in a way that its frame is inset from the Wrapper View precisely by your desired content inset.
Set clipsToBounds = false
on the Web View's scroll view (and true
on the Wrapper View).
Make sure that there is no content inset set on the Web View (webview.contentInset = .zero
).
(This is the default and normally, you don't need to set it at all).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With