Thomas Clayson
Thomas Clayson

Reputation: 29925

How to find out if a UIViewController is the root view controller?

basically I want to know if the view controller I'm in is the root view controller or not.

If its not I want to put a button in the nav bar that says "back" (as if it were a proper back button - this bit I know how to do).

Before you ask, I have removed all the titles from my view controllers - I didn't want them to show up on my navigation bar... its very complicated - but this means that when I go through my navigation stack none of the pushed view controllers have a back button. :/

Thanks Tom

Upvotes: 26

Views: 15773

Answers (3)

ZGski
ZGski

Reputation: 2528

Here's a swift version:

// Only works if checking from within the NavigationController:
navigationController?.viewControllers.first == self

// Works if you only have a reference to the NavigationController:
navigationController?.topViewController == navigationController?.viewControllers.first

Upvotes: 0

Warif Akhand Rishi
Warif Akhand Rishi

Reputation: 24248

You can also try:

if (self.navigationController.viewControllers.count == 1) {
    NSLog(@"self is RootViewController");
}

Upvotes: 15

Brian
Brian

Reputation: 15706

if ( self != [self.navigationController.viewControllers objectAtIndex:0] )
{
   // Put Back button in navigation bar
}

Upvotes: 77

Related Questions