无法在按钮单击时加载WebView

时间:2017-08-22 09:55:20

标签: swift macos webview

我正在尝试在动态创建的网页浏览中加载网址,当用户点击按钮但没有任何内容加载时。

代码:

import Cocoa
import WebKit

class ViewController :NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func mybutton(_ sender: Any) {
        let url = URL(string: "https://www.google.com")
        let request = URLRequest(url: url!)
        let webView =  WebView(frame: NSRect(x: 0, y: 0, width: 400, height: 400))
        webView.mainFrame.load(request)
    }

}

1 个答案:

答案 0 :(得分:2)

您仍然需要将WebView添加为ViewController的子视图:

@IBAction func mybutton(_ sender: Any) {
    let url = URL(string: "https://www.google.com")
    let request = URLRequest(url: url!)
    let webView =  WebView(frame: NSRect(x: 0, y: 0, width: 400, height: 400))
    webView.mainFrame.load(request)
    self.view.addSubview(webView)
}