获取iOS Swift中的所有UIViewControllers列表

时间:2016-07-26 07:47:20

标签: ios swift uiviewcontroller

有没有办法在iOS Swift Project中获取所有UIViewControllers。我想得到所有UIViewControllers的数组并检查是否存在特定的UIViewController。我必须在项目中找到特定的UIViewController是否存在。

2 个答案:

答案 0 :(得分:8)

您可以使用以下代码执行此操作。

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

if let viewControllers = appDelegate.window?.rootViewController?.presentedViewController
{
    // Array of all viewcontroller even after presented
}
else if let viewControllers = appDelegate.window?.rootViewController?.childViewControllers
{
    // Array of all viewcontroller after push                            
}

Swift 4.2(XCode 10)

let appDelegate = UIApplication.shared.delegate as! AppDelegate

if (appDelegate.window?.rootViewController?.presentedViewController) != nil
{
    // Array of all viewcontroller even after presented
}
else if (appDelegate.window?.rootViewController?.children) != nil
{
    // Array of all viewcontroller after push
}

答案 1 :(得分:3)

这是我根据prev答案进行的扩展

使用泛型+扩展(Swift 4.1)

/**
 * - Returns: ViewController of a class Kind
 * ## Examples: UIView.vc(vcKind: CustomViewController.self)//ref to an instance of CustomViewController
 */
public static func vc<T:UIViewController>(vcKind:T.Type? = nil) -> T?{
    guard let appDelegate:AppDelegate = UIApplication.shared.delegate as? AppDelegate else {return nil}
    if let vc = appDelegate.window?.rootViewController as? T {
        return vc
    }else if let vc = appDelegate.window?.rootViewController?.presentedViewController as? T {
        return vc
    }else if let vc = appDelegate.window?.rootViewController?.childViewControllers  {
        return vc.lazy.flatMap{$0 as? T}.first
    }
    return nil
}