찾다

 >  Q&A  >  본문

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일 전449

모든 응답(1)나는 대답할 것이다

  • 伊谢尔伦

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

    Swift 코드는 단순성에 주목합니다. 블록에 있지 않는 한 일반적으로 자체 포인터
    를 직접 사용할 필요는 없습니다.

    으아악

    중요: 현재 viewController에 NavigationController가 있는지 확인해야 합니다.

    회신하다
    0
  • 취소회신하다