UINavigationController:最简单的例子

时间:2010-06-19 23:23:00

标签: objective-c iphone

我正在尝试做一个非常简单的UINavigationController示例。这是我的代码:

- (void)viewDidLoad {
  [super viewDidLoad];

下一行有效,或者至少不会爆炸。

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

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

示例1.本行没有

  [navController pushViewController:one animated:NO];

示例2.本行工作(但当然没有导航控制器)

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

为什么我无法将ViewController实例推送到navController并看到屏幕更改?

注意:我意识到我的概念可能会向后倾斜而且我不需要让我的视图引用UINavigationController ...或其他东西。

2 个答案:

答案 0 :(得分:13)

- (void)viewDidLoad {
    [super viewDidLoad];

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

其背后的基本思想是导航控制器的根视图控制器是控制器,该视图将首先显示在导航控制器层次结构中。根控制器不是您将导航控制器插入的视图控制器。希望这会有所帮助。

答案 1 :(得分:4)

我只是重述@ E-ploko的答案,这是100%正确的(这就是为什么我标记它的最佳答案)。

您需要更多视图(和视图控制器)才能使用UINavigationController。其中一个房屋 UINavigationController,其rootViewController是该系列的第一页(没有“返回”的页面)。

我摆脱了代码示例的外部依赖关系:显然这是单片示例代码,而不是单片实际代码。

- (void)viewDidLoad {
    [super viewDidLoad];

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

    [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 gets reassigned. Not my clearest example ;)
    one = [[UIViewController alloc] init];

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

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