I have found many ways to pop back 2 UIViewControllers
in UINavigationController
using Objective-C, however when I try and switch that over to Swift it
I wrote an UIViewController extension (Swift 3+ ready)
You could use like this :
/// pop back n viewcontroller
func popBack(_ nb: Int) {
if let viewControllers: [UIViewController] = self.navigationController?.viewControllers {
guard viewControllers.count < nb else {
self.navigationController?.popToViewController(viewControllers[viewControllers.count - nb], animated: true)
return
}
}
}
Usage :
self.popBack(3)
Bonus dismiss to a specific viewcontroller
/// pop back to specific viewcontroller
func popBack(toControllerType: T.Type) {
if var viewControllers: [UIViewController] = self.navigationController?.viewControllers {
viewControllers = viewControllers.reversed()
for currentViewController in viewControllers {
if currentViewController .isKind(of: toControllerType) {
self.navigationController?.popToViewController(currentViewController, animated: true)
break
}
}
}
}
Usage :
self.popBack(toControllerType: MyViewController.self)