如何从AppDelegate获取当前可见的viewController

时间:2017-09-06 14:18:24

标签: ios swift

所以,我正在使用UIApplication扩展名下面的方法获取顶视图控制器:

    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let navigationController = controller as? UINavigationController {
        return topViewController(controller: navigationController.visibleViewController)
    }
    if let tabController = controller as? UITabBarController {
        if let selected = tabController.selectedViewController {
            return topViewController(controller: selected)
        }
    }
    if let presented = controller?.presentedViewController {
        return topViewController(controller: presented)
    }
    return controller
}

但问题是:它总是返回UIViewController。但我需要检查它是否为MyViewController。我如何实现这一目标?

5 个答案:

答案 0 :(得分:2)

对返回值进行条件转换以安全地检查其类型。

if let currentVC = UIApplication.topViewController() as? MyViewController {
   //the type of currentVC is MyViewController inside the if statement, use it as you want to
}

你的整个函数实现是有缺陷的,如果它确实有效,它将导致无限递归。一旦在if语句中找到当前顶视图控制器的类型,就会再次使用当前根控制器作为其输入值调用相同的函数。只有来自视图控制器的调用时,您的函数才会存在,该类的类不是可选绑定中指定的类。

此外,您的整个实施目前都没有做任何事情。您可以找到根视图控制器的类型,但是通过返回类型为UIViewController的值来向上转发它。

答案 1 :(得分:2)

UIViewController用作MyViewController

if let myViewController = UIApplication.topViewController() as? MyViewController { ... }

或者如果您只是想检查UIViewController是否为MyViewController类型:

if UIApplication.topViewController() is MyViewController { ... }

答案 2 :(得分:2)

您可以使用if-let语句进行条件检查,如下所示:

if let presented = controller?.presentedViewController as? MyViewController {
    // it is a MyViewController
}

你也可以直接检查UIViewController是否是这种类型的类:

if controller?.presentedViewController is MyViewController {
    // it is a MyViewController
}

答案 3 :(得分:1)

试试这个:

if let presented = controller?.presentedViewController as? MyViewController {
    ...

答案 4 :(得分:1)

您可以通过以下方式查看

class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        else if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        else if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
}


        // Answer 
        if let topVC = AppDelegate.topViewController() as? MyViewController {
            // Here your topVC is MyViewController
        }


        // or 
        if let topVC = AppDelegate.topViewController() {

            if topVC is MyViewController {
                // Here your topVC is MyViewController
            }
        }