Get all list of UIViewControllers in iOS Swift

爷,独闯天下 提交于 2021-02-07 06:44:06

问题


Is there any way to fetch all UIViewControllers in iOS Swift Project. I want to get array of all the UIViewControllers and check whether particular UIViewController exists or not.I have to just find the particular UIViewController exists or not in project.


回答1:


You can do it with below code.

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
}



回答2:


Here is an extension I made on the basis of prev answers

Uses Generics + Extension (🔸Swift 5.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 = UIApplication.shared.delegate, let window = appDelegate.window else { return nil }
     if let vc = window?.rootViewController as? T {
         return vc
     } else if let vc = window?.rootViewController?.presentedViewController as? T {
         return vc
     } else if let vc = window?.rootViewController?.children {
         return vc.lazy.compactMap { $0 as? T }.first
     }
     return nil
 }


来源:https://stackoverflow.com/questions/38583941/get-all-list-of-uiviewcontrollers-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!