2017-08-22 121 views
1

我想加載一個動態創建的web視圖上的網址,當用戶點擊一個按鈕,但沒有加載。無法加載按鈕點擊的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) 
    } 

} 

回答

2

你仍然需要你的WebView添加爲您的視圖控制器的子視圖:

@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) 
}