Parent view navigationController

simonbs picture simonbs · Feb 20, 2011 · Viewed 7.6k times · Source

I have a view which is a part of a tabBarController. In this view I have a subview with a table. When clicking a cell in this table, I would like to access the navigationController of the parent view. Is this possible - and if so, how?

I thought it would be

BandDetailViewController *bandDetailViewController = [[BandDetailViewController alloc] initWithNibName:@"BandDetailViewController" bundle:nil];
bandDetailViewController.band = [thisDay objectAtIndex:indexPath.row];

[super.navigationController pushViewController:bandDetailViewController animated:YES];
[bandDetailViewController release];

But that does not work.

Answer

Rayfleck picture Rayfleck · Feb 20, 2011

When you instantiate your sub-view controller, pass in a reference to the navigation controller (super's), and store it in an instance variable. You can then reference it when you need it in the sub. I have been looking for a more elegant solution to this and similar problems, without success. Passing in a reference works, so I do that and try to get on with my life.

EDIT: add code sample

In mainVC.m

 // this might be in didSelectRowForIndexPath:
 SubViewController *subVC = [[SubViewController alloc] init];
 subVC.superNavController = self.navController;
 [self.navigationController pushViewController:subVC animated:YES];

In SubViewController.h

 @property (nonatomic, retain) UINavigationController *superNavController;

In SubViewController.m

  @synthesize superNavController;


  // then, wherever you need it, say to pass to a sub-sub-viewController...
  [self.superNavController pushViewController:myNewVC animated:YES];