views:

55

answers:

2

I'm trying to do very simple example of a UINavigationController. Here is my code:

- (void)viewDidLoad {
  [super viewDidLoad];

This next line works, or at least doesn't blow up.

  navController = [[UINavigationController alloc] initWithRootViewController:self];
  self.title = @"blah";

  PageOneController *one = [[[PageOneController alloc]init] autorelease];

Example 1. THIS LINE DOES NOTHING

  [navController pushViewController:one animated:NO];

Example 2. THIS LINE WORKS (but no nav controller, of course)

  [self.view addSubview:one.view];
}

Why am I unable to push ViewController instances onto the navController and see the screen change?

Note: I realize that I might have my concepts backwards and I don't need to have my view referencing a UINavigationController... or something.

+1  A: 
- (void)viewDidLoad {
    [super viewDidLoad];

    PageOneController *one = [[[PageOneController alloc]init] autorelease];
    one.title = @"blah";
    navController = [[UINavigationController alloc] initWithRootViewController:one];
    [self.view addSubview:navController.view];
}

The basic idea behind it is that a navigation controller's root view controller is the controller which view will be displayed first in the navigation controller hierarchy. The root controller is not the view controller that you plug the navigation controller into. Hope this helps.

E-ploko
Perfect answer. Thanks and good luck on SO.
Yar
A: 

I'm just restating @E-ploko's answer, which is 100% correct (which is why I marked it best answer).

You need more views (and view controllers) to use the UINavigationController. One of them houses the UINavigationController, and its rootViewController is the first page of the series (the one that has no "back").

I got rid of the external dependencies for the code sample: obviously this is monolithic sample code, not monolithic real code.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIViewController *one = [[[UIViewController alloc] init] autorelease];

    [one.view setBackgroundColor:[UIColor yellowColor]];
    [one setTitle:@"One"];

    navController = [[UINavigationController alloc] initWithRootViewController:one];
    // here 's the key to the whole thing: we're adding the navController's view to the 
    // self.view, NOT the one.view! So one would be the home page of the app (or something)
    [self.view addSubview:navController.view];

    one = [[[UIViewController alloc] init] autorelease];

    [one.view setBackgroundColor:[UIColor blueColor]];
    [one setTitle:@"Two"];

    // subsequent views get pushed, pulled, prodded, etc.
    [navController pushViewController:one animated:YES];
}
Yar