Reputation: 392
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.
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.
I'm using InterfaceBuild with XIB files wire up the view.
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.
Upvotes: 5
Views: 5539
Reputation: 55554
To get as close to what Cmd +/- does in Safari/Chrome I increase the frame of the WKWebView and then transform the layer in the inverse:
var zoomLevel: CGFloat = 1
private func didTapZoomOut() {
zoomLevel -= 0.2
needsLayout = true
}
override func layout() {
super.layout()
webView.frame.size = CGSize(width: frame.width * (1/zoomLevel), height: frame.height * (1/zoomLevel))
webView.layer?.transform = CATransform3DMakeScale(zoomLevel, zoomLevel, 1)
}
This also causes the scrollbar to shrink but for my use case this isn't important.
Upvotes: 3
Reputation: 1475
@mattsven answer seems to be the right one.Here's the objective c variant of his solution:
NSString *jsCommand = [NSString stringWithFormat:@"document.body.style.zoom = 1.5;"];
[[wkWebView evaluateJavaScript:jsCommand completionHandler:^(NSString *result, NSError *error) {
if(error != nil) {
NSLog(@"Error: %@",error);
return;
}
NSLog(@" Success");
}];
It seems that WKWebView doesn't has a scalePagesToFit as UIWebView of iOS.
Upvotes: 2
Reputation: 23263
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)
Upvotes: 5