语言:swift 3.0
os:macOS 10.12.3
xcode:8.2.1
这是一个带有ViewController的空白Storyboard。
以下是代码:
import UIKit
import WebKit
class CommonWebViewViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
let backButton = UIBarButtonItem(title: "BACK", style: .plain, target: self, action: #selector(goBack))
let closeButton = UIBarButtonItem(title: "CLOSE", style: .plain, target: nil, action: #selector(close))
let webview = WKWebView()
var url = ""
override func viewDidLoad() {
super.viewDidLoad()
view = webview
navigationItem.setLeftBarButtonItems([backButton], animated: true)
webview.uiDelegate = self
webview.navigationDelegate = self
webview.allowsBackForwardNavigationGestures = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
func load(withUrl url: String) {
self.url = url
webview.load(URLRequest(url: URL(string: self.url)!))
}
func goBack() {
if webview.canGoBack {
webview.goBack()
navigationItem.leftBarButtonItems?.append(closeButton)
}
else {
close()
}
}
func close() {
_ = self.navigationController?.popViewController(animated: true)
}
}
我想制作一个浏览器,当我点按“返回”按钮时,除非我点击网页浏览中的链接,否则没有响应。
P.S如果我在viewDidload方法中创建UIBarButtonItem对象,问题就会解决。