LoginSignup
20
16

More than 3 years have passed since last update.

【Swift】最前面のViewControllerの取得方法(備忘録)

Last updated at Posted at 2019-08-03

最前面のViewControllerの取得方法が、しばしば記憶から消えるので備忘録的に。

お手軽パターン

ViewControllerExtension.swift

func topViewController() -> UIViewController? {
        var vc = UIApplication.shared.keyWindow?.rootViewController
        while vc?.presentedViewController != nil {
            vc = vc?.presentedViewController
        }
        return vc
    }

大体の場合、Google先生に聞いた時はこちらが出てくる。
presentでViewControllerをどんどん重ねていく系のアプリではこれでも問題がない。

が、NavigationControllerやTabBarControllerを使っている場合、それらの中身までは判定できない。
つまり、返り値がNavigationControllerやTabBarControllerになってしまう。
大抵の場合、それではNGなことが多いので次の方法を考える。

少し改善したパターン

ViewControllerExtension.swift
func topViewController(controller: UIViewController?) -> UIViewController? {
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }

        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }

        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }

        return controller
    }

こちらのパターンだと、NavigationControllerやTabBarControllerに当たっても、その中身までを吟味するため正確なViewControllerを取得することができる。

20
16
0

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
20
16