IOS显示动态创建的导航栏中的不同视图

时间:2011-05-03 10:22:32

标签: ios uiviewcontroller uinavigationcontroller

我需要动态添加一个包含带多个按钮的导航栏的UIViewController。当按下其中一个按钮时,我需要将显示的视图换成另一个按钮,同时保持导航栏。

CGRect appFrame = [[UIScreen mainScreen] applicationFrame]; 

ViewControllerOne* viewOne = [[ViewControllerOne alloc] init];
[viewOne.view setFrame:appFrame];  

UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44.01)]; 
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];

UIBarButtonItem* bi = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(back:)];
[buttons addObject:bi];
[bi release];

bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[buttons addObject:bi];
[bi release];

bi = [[UIBarButtonItem alloc] initWithTitle:@"Two" style:UIBarButtonItemStyleBordered target:self action:@selector(showTwo:)];
[buttons addObject:bi];
[bi release];

[tools setItems:buttons animated:NO];
[buttons release];
viewOne.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
[tools release];

m_navViewController = [[UINavigationController alloc] initWithRootViewController:viewOne];
[m_navViewController.view setFrame: appFrame ];
[self addSubview: m_navViewController.view];

现在有人按下两个按钮我想删除viewOne并添加一个ViewControllerTwo对象

 - (void) showTwo:(id)sender{
    ViewControllerTwo* viewTwo = [[ViewControllerOne alloc] init];
    [viewOne.view setFrame:[[UIScreen mainScreen] applicationFrame]]; 

    // remove viewOne from m_navViewController and add viewTwo
}

换句话说,我想通过按导航栏中的一个项目来显示不同的视图,但为所有视图保留相同的导航栏。

请注意导航栏实际上会有五个按钮。我已将其简化为解释目的。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用导航控制器模板;将按钮添加到IB中的导航栏(或上面的代码中),然后当点击其中一个按钮时,按下相应的视图控制器。