因为@matt的回答不完整,所以在推下一个视图控制器之前,我的解决方案是等待WebView加载:
class TableViewController: UITableViewController, WKNavigationDelegate, WKUIDelegate {
var webviewToLoad:WKWebView!
var destinationController:ViewController!
var alert:UIAlertController!
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
alert = UIAlertController(title: "Alert", message: "Loading", preferredStyle: .alert)
destinationController = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController") as? ViewController
destinationController!.loadViewIfNeeded()
let webView:WKWebView = destinationController!.webView
webView.navigationDelegate = self
webView.uiDelegate = self
self.present(alert, animated: true, completion: nil)
let htmlString = "my html code"
webView.loadHTMLString(htmlString, baseURL: Bundle.main.resourceURL)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
alert.dismiss(animated: false, completion: nil)
self.navigationController?.pushViewController(destinationController!, animated: true)
}
}
以及内置WebView的uiviewController:
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
var webView: WKWebView!
@IBOutlet var viewForWebview: UIView!
@IBOutlet var heightWebviewConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
webView = WKWebView()
if (webView != nil) {
webView!.frame = viewForWebview.frame
webView.translatesAutoresizingMaskIntoConstraints = false
viewForWebview.addSubview(webView!)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: viewForWebview.topAnchor),
webView.bottomAnchor.constraint(equalTo: viewForWebview.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: viewForWebview.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: viewForWebview.trailingAnchor)
])
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
heightWebviewConstraint.constant = self.webView.scrollView.contentSize.height
self.view.setNeedsLayout()
self.view.setNeedsUpdateConstraints()
}
}
此代码在WebView加载期间显示一个uiAlertController,然后关闭警报控制器,并推送下一个已加载WebView的控制器。