更改后栏按钮项的操作

时间:2017-07-07 18:35:49

标签: ios swift

我希望能够更改导航控制器中特定UIViewController上的后栏按钮项的操作,以便弹出到根视图控制器。我尝试了以下但是他们不能工作:

let backButton = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(back))
self.navigationItem.backBarButtonItem = backButton

self.navigationItem.backBarButtonItem?.action = #selector(back)

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

首先backBarButtonItem操作不起作用,因为您只能更改后退按钮标题,看一看它的问题here

解决方案

在ViewController中,要从中弹出根ViewController,您需要设置为UINavigationControllerDelegate的委托

override func viewDidLoad() {
    super.viewDidLoad()

     navigationController?.delegate = self
}

并实现UINavigationControllerDelegate这个方法`

func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
    if viewController.isKind(of:PreviousViewController.self) {
        navigationController.popToRootViewController(animated: animated)
    }
}

如果我的答案不符合您的要求,您可以查看类似问题here

答案 1 :(得分:0)

您应该使用self.navigationItem.leftBarButtonItem = backButton

祝你好运

答案 2 :(得分:0)

要保持后退按钮的外观和感觉,但更改操作,请参阅ViewWillDisappear对问题的回答,"按下UINavigationController的后退按钮时执行操作" Execute action when back bar button of UINavigationController is pressed

答案 3 :(得分:-2)

这是您的解决方案,仅需设置目标和选择器即可。

 private func setNavBar() {
    let item = navigationItem.backBarButtonItem
    item?.target = self
    item?.action = #selector(self.donePressed)
    navigationItem.leftBarButtonItem = item
}

 @objc private func donePressed() {
    self.dismiss(animated: true, completion: nil)
}