98
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-10-20

参考

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?.popViewController(animated: true)

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

実践的な方法

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

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)
98
87
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
98
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?