26

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

Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224
  • 1
    You can achieve the same thing by just setting the backBarButtonItem property of the navigationItem of each view controller. The navigation controller will use that instead of the title and take care of the navigation for you. – Firoze Lafeer Oct 28 '10 at 15:59
  • oh right.... is there a way to do that to every single back button in the app? For instance with some category code or something? – Thomas Clayson Oct 28 '10 at 16:04
  • If you have a lot of view controller classes but you want the back items to be the same in each, you could create a common parent for those controllers and set the item in that init. – Firoze Lafeer Oct 28 '10 at 16:16

3 Answers3

77
if ( self != [self.navigationController.viewControllers objectAtIndex:0] )
{
   // Put Back button in navigation bar
}
Brian
  • 15,599
  • 4
  • 46
  • 63
15

You can also try:

if (self.navigationController.viewControllers.count == 1) {
    NSLog(@"self is RootViewController");
}
Warif Akhand Rishi
  • 23,920
  • 8
  • 80
  • 107
0

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
ZGski
  • 2,398
  • 1
  • 21
  • 34