UINavigationControllerで2つ以上前の画面に戻る方法


参考

How do I pop two views at once from a navigation controller?


実装方法

// rootViewControllerに戻る

navigationController?.popToViewController(navigationController!.viewControllers[0], animated: true)
// または
navigationController?.popToRootViewControllerAnimated(true)

// rootViewControllerの1つ先のViewControllerに戻る
navigationController?.popToViewController(navigationController!.viewControllers[1], animated: true)

// rootViewControllerの2つ先のViewControllerに戻る
navigationController?.popToViewController(navigationController!.viewControllers[2], animated: true)

// 1つ前のViewControllerに戻る
navigationController?.popViewControllerAnimated(true)

// 2つ前のViewControllerに戻る
let index = navigationController!.viewControllers.count - 3
navigationController?.popToViewController(navigationController!.viewControllers[index], animated: true)


実践的な方法

以下のStackoverflowで紹介されているように、UINavigationControllerを拡張すると便利です。

https://stackoverflow.com/a/23650545


UINavigationController+.swift

extension UINavigationController {

func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.filter({$0.isKind(of: ofClass)}).last {
popToViewController(vc, animated: animated)
}
}

func popViewControllers(viewsToPop: Int, animated: Bool = true) {
if viewControllers.count > viewsToPop {
let vc = viewControllers[viewControllers.count - viewsToPop - 1]
popToViewController(vc, animated: animated)
}
}
}



HowToUse.swift

// pop to SomeViewController class

navigationController?.popToViewController(ofClass: SomeViewController.self)

// pop 2 view controllers
navigationController?.popViewControllers(viewsToPop: 2)