There are three possiblities.
Case 1: If the view controller is embedded in UINavigationController
Case 2: If the view controller is embedded in UITabControllerBar
Case 3: If the view controller is presented via other UIViewController
So we have to traverse through the possible combination until we reach the topmost layer.
#pragma mark- View Hierarchy-
+ (UIViewController*)topViewController {
return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
+ (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
//Type 1: Travese in tabbar controller-
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
//Type 2: Travese in navigation controller-
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
//Type 3: Travese in view controller-
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
ReplyDeleteThank you for your post. This is excellent information. It is amazing and wonderful to visit your blog.
ios app development course
iPhone training institute in bangalore
Xcode iPhone/iPad find the top View Controller in the current View Hierarchy
ReplyDeleteVery informative post about iOS developers...
Read our blog - 5 Benefits of Hiring skilled iOS developers for your Enterprise
hire iOS developers