經(jīng)常會遇到一些場景, 要通過代碼獲取到當前顯示在屏幕最頂層的UIViewController. 如何獲取呢?
獲取rootViewController
The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.
rootViewController的設定通常會在設置keyWindow的時候遇到, 表示該UIWindow的最底層的UIViewController.
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = keyWindow.rootViewController;
獲取currentViewController
一般情況下, 可通過如下方式獲取當前屏幕最頂層的ViewController:
- (UIViewController *)currentViewController {
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *vc = keyWindow.rootViewController;
while (vc.presentedViewController) {
vc = vc.presentedViewController;
if ([vc isKindOfClass:[UINavigationController class]]) {
vc = [(UINavigationController *)vc visibleViewController];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
vc = [(UITabBarController *)vc selectedViewController];
}
}
return vc;
}