有没有办法在整个UINavigationController堆栈中保持按钮?

时间:2012-03-04 21:48:38

标签: ios cocoa-touch uinavigationcontroller

我知道如何向每个控制器添加一个按钮,我将其推入导航控制器堆栈。 但是我需要在导航栏的右上角有一个设置按钮,无论哪个控制器被推或弹出。该按钮应以模态方式显示设置viewController。

对我来说,让每个控制器的viewDidLoad包含按钮的代码加上包括设置控制器标题似乎是一个黑客。

似乎我应该能够从导航控制器本身插入此按钮,指向导航控制器中的选择器。然后,此方法将以模态方式呈现settingsController,通过该堆栈中当前处于活动状态的控制器。

关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:3)

好的,这就是我所做的:

1 - 子类UINavigationController并包含我的设置控制器的标题

2 - 覆盖 -pushViewController:aniamted:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [super pushViewController:viewController animated:animated];
    UIBarButtonItem *settingsButton = [[UIBarButtonItem alloc]initWithTitle:@"Settings" 
                                                                      style:UIBarButtonItemStylePlain 
                                                                     target:self
                                                                     action:@selector(shouldPresentSettingsView)];
    [viewController.navigationItem setRightBarButtonItem: settingsButton];
    [settingsButton release];
}

3 - 添加两种方法:

- (void)shouldPresentSettingsView
{
    SetupViewController *settingsView = [[SetupViewController alloc] init];
    UINavigationController *tempController = [[UINavigationController alloc]initWithRootViewController:settingsView];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" 
                                                                     style:UIBarButtonItemStylePlain 
                                                                    target:self 
                                                                    action:@selector(shouldDismissSettingsView)];
    settingsView.navigationItem.leftBarButtonItem = cancelButton;
    [self.visibleViewController presentModalViewController:tempController animated:YES];

    [cancelButton release];
    [settingsView release];
    [tempController release];
}

- (void)shouldDismissSettingsView
{
    [self dismissModalViewControllerAnimated:YES];
}

答案 1 :(得分:2)

将导航控制器的委托设置为全局,例如应用委托。在该对象中,初始化UIBarButtonItem并保存到实例变量:

- (void)setupSettingsButton
{
    settingsBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
                                                                      target:self 
                                                                      action:@selector(openSettings)];
}

然后在推送之前配置每个视图控制器的navigationItem:

- (void)navigationController:(UINavigationController *)aNavigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    viewController.navigationItem.rightBarButtonItem = settingsBarButton;
}

并处理按钮操作...

- (void)openSettings
{
    [navigationController presentViewController:settingsVC animated:YES completion:NULL];
}