當(dāng)視圖層級(jí)很深的時(shí)候贰谣,如何獲取當(dāng)前視圖的控制器构罗?
獲取根視圖控制器的方法
方法一
思路:遍歷當(dāng)前視圖的父視圖,獲取控制器
func responseUIViewController() -> UIViewController?{
for view in sequence(first: self.superview, next: { $0?.superview }){
if let response = view?.next{
if response.isKind(of: UIViewController.self){
return response as? UIViewController
}
}
}
return nil
}
方法二
思路:獲取當(dāng)前視圖的根視圖控制器
private func responseUIViewController() -> UIViewController?{
guard let vc = UIApplication.shared.windows.first else {
return nil
}
return vc.rootViewController
}