我希望能够更改导航控制器中特定UIViewController
上的后栏按钮项的操作,以便弹出到根视图控制器。我尝试了以下但是他们不能工作:
let backButton = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(back))
self.navigationItem.backBarButtonItem = backButton
和
self.navigationItem.backBarButtonItem?.action = #selector(back)
有什么建议吗?
答案 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)
}