你
可以
只需创建并添加
WKWebView
通过代码。
如果您想在故事板中为布局目的提供视觉表现,这里有一种方法。
添加标准
UIView
在故事板的视图控制器中。这将充当web视图的“持有者”。将其连接到
IBOutlet
viewDidLoad
添加的实例
作为该“holder”视图的子视图。
class MyViewController: UIViewController, WKNavigationDelegate {
// standard UIView, added in Storyboard
@IBOutlet weak var webViewHolder: UIView!
// instance of WKWebView
let wkWebView: WKWebView = {
let v = WKWebView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
// add the WKWebView to the "holder" UIView
webViewHolder.addSubview(wkWebView)
// pin to all 4 edges
wkWebView.topAnchor.constraint(equalTo: webViewHolder.topAnchor, constant: 0.0).isActive = true
wkWebView.bottomAnchor.constraint(equalTo: webViewHolder.bottomAnchor, constant: 0.0).isActive = true
wkWebView.leadingAnchor.constraint(equalTo: webViewHolder.leadingAnchor, constant: 0.0).isActive = true
wkWebView.trailingAnchor.constraint(equalTo: webViewHolder.trailingAnchor, constant: 0.0).isActive = true
// load a URL into the WKWebView
if let url = URL(string: "https://google.com") {
wkWebView.load(URLRequest(url: url))
}
// from here on out, use wkWebView just as if you had added it in your storyboard
}
}