首页 > 解决方案 > 如何在容器视图中显示 WKWebView 内容

问题描述

以下代码正在运行,但问题是此视图位于导航中,因此 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
}

}

标签: iosswiftuinavigationcontrollerwkwebview

解决方案


设置框架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),
])

推荐阅读