更改导航后退按钮的目的地 [英] Change destination of Navigation Back button
问题描述
如何更改默认导航后退按钮带我到的视图控制器?后退按钮通常会将您带回到上一个视图控制器。但是,如果我希望它由两个视图控制器返回呢?我的意思是我想改变后退按钮带我到的视图控制器。我不喜欢创建自定义后退按钮。那么还有其他方法吗?可能是一个与后退按钮相关联的展开segue?
How can I change the view controller the default navigation back button takes me to? The back button usually takes you back to the previous view controller. But what if I want it to go back by two view controllers? I mean I want to change the view controller the back button takes me to. I do not prefer creating a custom back button. So is there any other way? Probably an unwind segue linked to the back button or something?
推荐答案
实现所需行为的最简单方法是使用 navigationController.setViewControllers(控制器,动画:true)
。
Probably easiest way to achieve behaviour you want is to use navigationController.setViewControllers(controllers, animated: true)
.
如果你想从控制器A返回2个控制器而不是只有一个,在呈现A时使用此自定义segue:
If you want to go 2 controllers back from controller A instead of only one, use this custom segue when presenting A:
class ReplaceControllerSegue: UIStoryboardSegue {
override func perform() {
if let navigationController = sourceViewController.navigationController as UINavigationController? {
var controllers = navigationController.viewControllers
controllers.removeLast()
controllers.append(destinationViewController)
navigationController.setViewControllers(controllers, animated: true)
}
}
}
这是一个很好的教程如何为你的segue设置自定义类在Interface Builder中: http://blog.jimjh.com /a-short-tutorial-on-custom-storyboard-segues.html
Here is nice tutorial how to set custom class for your segue in Interface Builder: http://blog.jimjh.com/a-short-tutorial-on-custom-storyboard-segues.html
如果您通过代码展示控制器,请使用以下类别:
If you are presenting controller via code, use this category:
extension UINavigationController {
func replaceCurrentViewControllerWith(viewController: UIViewController, animated: Bool) {
var controllers = viewControllers
controllers.removeLast()
controllers.append(viewController)
setViewControllers(controllers, animated: animated)
}
}
然后只需使用 self.navigationController!.replaceCurrentViewControllerWith(newController,animated:true)
而不是 self.navigationControllerPushViewController(newController,animated:true)
。
Then just use self.navigationController!.replaceCurrentViewControllerWith(newController, animated: true)
instead of self.navigationControllerPushViewController(newController, animated: true)
.
调整此代码可以轻松删除所需的控制器。
It's easy to adjust this code to remove as much controllers as you need.
这篇关于更改导航后退按钮的目的地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!