In addition to providing menus, navigation
controllers do the job they are designed to do: managing hierarchy as
you navigate between views. Recipe 1 introduces the navigation controller as an actual navigation controller, pushing views on the stack.
An
instance variable stores the current depth number, which is used to show
the current level and decide whether to display a further push option.
The maximum depth here is 6. In real use, you’d use more meaningful view
controllers or contents. This sample demonstrates things at their
simplest level.
The navigation controller automatically creates the Level 2 Back button shown in Figure 1
(left) as an effect of pushing the new Level 3 controller onto the
stack. The rightmost button (Push 4) triggers navigation to the next
controller by calling pushViewController: animated:. When pushed, the next Back button reads Level 3, as shown in Figure 1 (right).
Back buttons pop the
controller stack for you. You do not need to program any popping
behavior yourself. Note that Back buttons are automatically created for
pushed view controllers but not for the root controller itself, as it is
not applicable.
Recipe 1. Drilling Through Views with UINavigationController
@interface TestBedViewController : UIViewController { int depth; } @end
@implementation TestBedViewController - (id) initWithDepth: (int) theDepth { self = [super init]; if (self) depth = theDepth; return self; }
- (void) push { TestBedViewController *tbvc = [[[TestBedViewController alloc] initWithDepth:(depth + 1)] autorelease]; [self.navigationController pushViewController:tbvc animated:YES]; }
- (void) loadView { self.view = [[[NSBundle mainBundle] loadNibNamed:@"mainview" owner:self options:nil] lastObject]; NSString *valueString = [NSString stringWithFormat:@"%d", depth]; NSString *nextString = [NSString stringWithFormat:@"Push %d", depth + 1];
// set the title self.title = [@"Level " stringByAppendingString:valueString];
// Set the main label ((UILabel *)[self.view viewWithTag:101]).text = valueString;
// Add the "next" bar button item. Max depth is 6 if (depth < 6) self.navigationItem.rightBarButtonItem = BARBUTTON(nextString, @selector(push)); } @end
|