search

Home  >  Q&A  >  body text

ios - swift 使用wkwebview,添加了一个导航栏,网导航栏上添加不了东西怎么解决?

在使用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.
}

}

高洛峰高洛峰2771 days ago451

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:49:41

    Swift code pays attention to simplicity. Unless it is in a block, the self pointer is generally not used
    Use it directly:

    title = webView.title

    Important: You should check whether the navigationController in your current viewController exists.

    reply
    0
  • Cancelreply