且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改导航后退按钮的目的地

更新时间:2022-11-05 13:22:15

实现所需行为的最简单方法是使用 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.