Home > other >  WKWebView view not resizable
WKWebView view not resizable

Time:02-11

I'm creating a macOS Swift app, I'm new to Swift. I'm trying to make the view resizable like web browsers (Chrome, Firefox, etc.), however my code doesn't seem to work, and I didn't find anything useful about WKWebView resizing.

Here's my code for the ViewController:

import Cocoa
import WebKit

class ViewController: NSViewController, WKUIDelegate
    {
    var webView: WKWebView!

    override func loadView()
    {
        let webConfiguration = WKWebViewConfiguration ();
        webConfiguration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs");
        webView = WKWebView (frame: CGRect(x:0, y:0, width:1920, height:1080), configuration:webConfiguration);
        webView.uiDelegate = self;
            self.view = webView;
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
        self.view.addSubview(webView)
        let url = URL(string: "https://www.google.com/")
        webView.load(URLRequest(url: url!))
    }  
}

Results: Does not resize webview when window is resized

CodePudding user response:

Okay so I figured out how to fix the issue with Willeke's recommendation:

Replace this:

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
self.view.addSubview(webView)
let url = URL(string: "https://www.google.com/")
webView.load(URLRequest(url: url!))

With this:

if let url = URL(string: "https://www.roblox.com/") {
    let request = URLRequest(url: url)
    webView.load(request)
}
  • Related