在使用wkwebview的时候,想给导航栏上加上访问页面的title,以及想添加UIBarButtonItem,但是都添加不了.
代码如下:
import UIKit
import WebKit
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height
class ViewController: UIViewController,WKNavigationDelegate {
var webView = WKWebView()
var btnBack = UIBarButtonItem()
var btnForward = UIBarButtonItem()
override func viewDidLoad() {
super.viewDidLoad()
setNavBar()
self.webView.navigationDelegate = self
let cgrect1:CGRect = CGRect(x: 0, y: 44+20, width: WIDTH, height:HEIGHT)
//创建webview
let webView:WKWebView = WKWebView(frame: cgrect1)
let url = NSURL(string: "https://www.baidu.com")
let request = NSURLRequest(url: url as! URL)
webView.load(request as URLRequest)
self.view.addSubview(webView)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.navigationItem.title = self.webView.title
}
func setNavBar(){
btnBack = UIBarButtonItem(title: "后退", style: .plain, target: self, action: #selector(toBack))
btnBack.tintColor = UIColor.blue
btnForward.tintColor = UIColor.blue
btnForward = UIBarButtonItem(title: "前进", style: .plain, target: self, action: #selector(toForward))
navigationController?.navigationItem.leftBarButtonItem = btnBack
navigationController?.navigationItem.rightBarButtonItem = btnForward
}
func toBack(){
if self.webView.canGoBack {
self.webView.goBack()
}else{
print("====")
}
}
func toForward(){
if self.webView.canGoForward {
self.webView.goForward()
}else{
print("-----")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Le code Swift fait attention à la simplicité. Sauf s'il s'agit d'un bloc, il n'est généralement pas nécessaire d'utiliser le self pointeur
directement :
Important : vous devez vérifier si le navigationController dans votre viewController actuel existe.