搜索

首页  >  问答  >  正文

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 天前450

全部回复(1)我来回复

  • 伊谢尔伦

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

    swift 代码讲究简洁。 除非是在 block 中,否则一般不用 self 指针
    直接使用:

    title = webView.title

    重点:你应该检查一下你当前的 viewController 中 navigationController 是否存在。

    回复
    0
  • 取消回复