Resizing WKWebView height on zoom iOS

I have a table view where each cell contains a WKWebView of HTML content. Initially the content has its size to fit a prescribed width and height.


What I want to do is allow users to zoom in and out of the WKWebView and while adjusting the height of the cell view.


To give some context what I did was attach a Javascript (WKUserScript) to the WKWebView and in the script it contains

window.onload = function () {
     window.webkit.messageHandlers.sizeNotification.postMessage({width: document.body.scrollWidth, height: document.body.scrollHeight});
}


What this does is when the HTML content is loaded, it will send the message with name "sizeNotification" to a UIViewController conforming to the WKScriptMessageHandler. The message contains the scrollHeight which is what I use to set the frame of the WKWebView by adjusting a height constraint.

I also save that scrollHeight value which will be important later.

After the user zooms in the WKWebView the delegate method scrollViewDidEndZooming gets called which contains the current scaled information of the WKWebView's scrollView. I set the new height constraint constant of the WKWebView's frame by


webViewHeightConstraint.constant = initialHeight * scale


The height of the WKWebView increases and since I used dynamic sizing cells, the table cell height will also adjust accordingly. 🙂


That is UNTIL the zoom scale reaches a value close to 1.0

If it gets higher than this value, the content inside the WKWebView/scrollView gets white padding at the bottom.


I suspect that this has to do with the Width/Height ratio of the WebView's frame being changed, since if the initial height of the WebView is greater than content height this will also happen. Another example would be if you open a webpage in Safari that has a content height of 300px but you stretched out the window to have a height of 100px, there would be white space at the bottom (or whatever <body> is set to)


My questions is if there's a fix/workaround for the white bottom padding issue? If you look at an email thread in Mail on iOS you can zoom in and out of the emails and the cell heights adjust accordingly.

5 years passed, anyone has a solution?

The problem is still exist, WKWebView will set a very large contentSize, if you zoomed out and change the webview's frame after zoom.

Resizing WKWebView height on zoom iOS
 
 
Q