這個方法只能獲取到當前頁面之前的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)")