Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView - content not fitting after magnification

I’m experiencing a problem with a WKWebView on setting the magnification property.

I expecting the content to resize to fit like it does in Safari. But I can’t achieve this. When setting the magnification to a value less than 1.0 is the following.

enter image description here

The extra space is not used and a margin occurs. In Safari zooming out results in smaller text and image size but the extra space is actually used.

enter image description here

I'm using InterfaceBuild with XIB files wire up the view.

enter image description here

enter image description here

enter image description here

Also, I enable magnification in viewDidLoad.

webView.allowsMagnification = YES;

I also tried the following with no success:

webView.translatesAutoresizingMaskIntoConstraints = NO;
webView.autoresizesSubviews = NO;
webView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;

Any hint would be very much appreciated.

like image 927
Jan Linxweiler Avatar asked May 10 '18 18:05

Jan Linxweiler


1 Answers

The problem is that WKWebView's magnification property doesn't do what you think it does. What it does is that it scales the rendered page as a whole (think taking a bitmap or image and resizing it).

What you want is the dynamic scaling capability that Safari (and other browsers) have, generally referred to as "zooming". This is different from magnification, as it scales the layout of the page. This scales up or down the font sizes, element sizes, and so on, of a page individually.

There's no native (public) API to zoom a page like Safari does, but you can do pretty much the same thing by taking advantage of the CSS zoom property. Here's an extension that does just that:

extension WKWebView {

    func zoom(to zoomAmount: CGFloat) {
        evaluateJavaScript("document.body.style.zoom = '\(zoomAmount)'", completionHandler: nil)
    }

}

It can be used like this:

webView.zoom(to: 0.9)
like image 181
mattsven Avatar answered Oct 27 '22 15:10

mattsven