'Swift WKWebview Initial zoom and magnification

I have a webview that zooms in and out properly via zoom scale.

However, I would like to set the initial zoom scale when the webview is loaded. For example, I would like the web view to be presented as if I pinched the web view all the way zoomed out max.

(Pinching inward to the center of the screen, not zooming in)

How can I initialize the webview to start out completely zoomed out?

// MARK: WebView
    lazy var webView: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        let webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.scrollView.delegate = self
        webView.navigationDelegate = self
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.contentMode = .center
        webView.scrollView.isScrollEnabled = true
        webView.allowsBackForwardNavigationGestures = false
        webView.scrollView.zoomScale = 2.0
        webView.backgroundColor = appGrey
  
        return webView
    }()


Solution 1:[1]

I have done it for objective-c, it is working right now in one of my apps, fell free to convert it to Swift ;) If I have some time I will edit this answer to add it. You have to setup the content, not the component.

NSString *_wa_initial_zoom = @"var meta = document.createElement('meta'); meta.name = 'viewport'; meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'; var head = document.getElementsByTagName('head')[0]; head.appendChild(meta);";

NSString *source = [self wkWebViewSetInitialZoomScale];
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
        
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
        
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.websiteDataStore = WKWebsiteDataStore.defaultDataStore;
wkWebConfig.userContentController = wkUController;
        
wkWebConfig.preferences = [[WKPreferences alloc] init];
wkWebConfig.preferences.minimumFontSize = 10;
// JavaScript
wkWebConfig.preferences.javaScriptEnabled = YES;
wkWebConfig.preferences.javaScriptCanOpenWindowsAutomatically = YES;
wkWebConfig.processPool = [[WKProcessPool alloc] init];
        
WKWebView *_wkWebView  = [[WKWebView alloc] initWithFrame:_wkWebView.bounds configuration:wkWebConfig];

This is a full setup in objective-c of a WKWebView load.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman