Show the UINavigationController Root View Controller in UITabBarController

A method for showing the UINavigationController Root View Controller in UITabBarController using introspection to determine class membership.

When programming on iPhone or iPad, it’s common to have a UITabBarController mixed with UINavigationController.

You will probably find yourself needing to show the Root View Controller of a Navigation Controller when you switch Tabs in the Tab Controller. In your UITabBarControllerDelegate you implement the following method.

By: Steven Vance


- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController;

Showing the Root View Controller is as easy as calling popToRootViewControllerAnimated. You’ll want to check the viewController parameter to see if it is a kind of UINavigationController. If it is, cast it and then call popToRootViewControllerAnimated.


- (void) tabBarController: (UITabBarController *) tabBarController 
                                        didSelectViewController: (UIViewController *) viewController {
	if ([viewController isKindOfClass:[UINavigationController class]]) {
		[(UINavigationController*)viewController popToRootViewControllerAnimated:NO];
	}
}

In this way, you won’t get warnings like the following.

'UIViewController' may not respond to '-popToRootViewControllerAnimated:' ...

That is what happens when you make the call on a UIViewController like this.


[viewController popToRootViewControllerAnimated:YES];

By using isKindOfClass to identify the kind of UIViewController, you will also be able to mix your View Controllers in your Tab Controller. The check for Class membership will ensure that your are only invoking the method on the right kinds of objects.

You can read more about Introspection in the Apple
Cocoa Fundamentals Guide.

Author: eric

Eric Holsinger is a software professional and photography enthusiast in Southern Maine.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.