如何在容器视图中显示 WKWebView 内容
How to display WKWebView content inside a container view
以下代码有效,但问题是此视图位于导航中,因此 html 内容位于导航后面。我想在安全区域内添加另一个容器视图,然后在那里显示 html 内容。我尝试添加一个容器视图并将 webView 分配给该容器视图,但它不起作用,因为屏幕显示黑色。谁能告诉我我们是否可以做到以及如何做到?
导入 UIKit
导入 WebKit
class MyViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
var content: String!
override func viewDidLoad() {
let htmlString = "<html><head><meta name='viewport' content='initial-scale=1.0'/></head><body>" + content
+ "</body></head></html>"
webView.loadHTMLString(htmlString, baseURL:nil)
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
webView.uiDelegate = self
view = webView
}
}
设置webView
的框架
webView.frame = CGRect(/* set x, y, wifth and height here*/)
或者使用一些自动布局约束
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(webView)
NSLayoutConstraint.activate([
webView.heightAnchor.constraint(equalToConstant: 300),
webView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
webView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
webView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])
以下代码有效,但问题是此视图位于导航中,因此 html 内容位于导航后面。我想在安全区域内添加另一个容器视图,然后在那里显示 html 内容。我尝试添加一个容器视图并将 webView 分配给该容器视图,但它不起作用,因为屏幕显示黑色。谁能告诉我我们是否可以做到以及如何做到?
导入 UIKit 导入 WebKit
class MyViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
var content: String!
override func viewDidLoad() {
let htmlString = "<html><head><meta name='viewport' content='initial-scale=1.0'/></head><body>" + content
+ "</body></head></html>"
webView.loadHTMLString(htmlString, baseURL:nil)
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
webView.uiDelegate = self
view = webView
}
}
设置webView
的框架
webView.frame = CGRect(/* set x, y, wifth and height here*/)
或者使用一些自动布局约束
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(webView)
NSLayoutConstraint.activate([
webView.heightAnchor.constraint(equalToConstant: 300),
webView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
webView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
webView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
])