检测applicationWillEnterForeground中存在哪个视图

时间:2018-04-24 10:37:27

标签: ios swift

我想知道应用程序前进时哪个视图存在。

这怎么可能?

func applicationWillEnterForeground(_ application: UIApplication) {

            if (storyboardID == "myview") {

               //do sth

            }

        }

2 个答案:

答案 0 :(得分:2)

isValid()

使用上面的代码,您将获得当前的View Controller。

使用示例

$editForm->getErrors(true, false)

答案 1 :(得分:1)

public extension UIWindow {
    public var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
    }

    public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            } else {
                return vc
            }
        }
    }
}

Swift中UIApplication的简单扩展(甚至关心UITabBarController中的moreNavigationController:

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController where top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

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

        return base
    }
}

简单用法:

   if let rootViewController = UIApplication.topViewController() {
        //do sth with root view controller
    }