这个方法只能获取到当前页面之前的vc
let windows = UIApplication.shared.windows
var controllers = [UIViewController]()
for window in windows {
if let rootVC = window.rootViewController {
controllers.append(rootVC)
// 如果需要包含导航控制器、标签页控制器等容器类型的子控制器,则使用以下代码进行深度优先搜索
func getAllChildViewControllers(_ viewController: UIViewController?) -> [UIViewController] {
var childViewControllers = [viewController].compactMap({ $0 })
for subviewController in viewController?.children ?? [] {
childViewControllers += getAllChildViewControllers(subviewController)
}
return childViewControllers
}
controllers.append(contentsOf: getAllChildViewControllers(rootVC))
}
}
debugPrint("controllerscontrollers=== \(controllers)")