如何获取顶层UIViewController

Objective-c版本:

1
2
3
4
5
6
7
8
- (UIViewController *)appRootViewController{
UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *topVC = appRootVC;
while (topVC.presentedViewController) {
topVC = topVC.presentedViewController;
}
return topVC;
}

swift 2.0版本:

1
2
3
4
5
6
7
8
9
10
11
extension UIApplication {

/// 顶层VC
static var appRootViewController: UIViewController? {
var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController
while topVC?.presentedViewController != nil {
topVC = topVC?.presentedViewController
}
return topVC
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!