向 UINavigationController 中的所有视图控制器添加相同的按钮 [英] Adding same button to all view controllers in UINavigationController

查看:17
本文介绍了向 UINavigationController 中的所有视图控制器添加相同的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UINavigationController(像向导页面一样使用),我以编程方式创建,我需要显示一个取消"按钮来取消任何 UIViewController 中的进程.

I have a UINavigationController (to use like a wizard page) which I create programmatically and I need to display a "Cancel" button to cancel the process in any UIViewController.

创建UINavigationController:

FirstVC *firstVC = [[[FirstVC alloc] initWithNibName:@"FirstPage" bundle:nil] autorelease];
firstVC.delegate = self;

navigationController = [[UINavigationController alloc] initWithRootViewController:firstVC];
[self.view addSubview:navigationController.view];

添加取消按钮:

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelRequestNewLeave:)];
navigationController.topViewController.navigationItem.rightBarButtonItem = cancelButton;
[cancelButton release];

但是当我将第二个页面推送到 UINavigationController 时,UINavigationBar 上没有显示取消按钮.如果我回到第一页,取消按钮就在那里.因此,显然该按钮仅针对第一个视图添加.我相信这是因为我没有继承 UINavigationController,因为我需要在子视图中使用它.但我不知道如何在以编程方式创建的 UINavigationController 中设置 rightBarButtonItem.

But when I push a second page to UINavigationController the cancel button is not shown on the UINavigationBar. If I go back to first page, the cancel button is there. So, apparently the button is added only for the first view. I believe this is because I'm not subclassing UINavigationController, because I need to use it in a subview. But I don't know how to set the rightBarButtonItem in a UINavigationController which is created programmatically.

navigationController.topViewController.navigationItem.rightBarButtonItem = cancelButton;

有人可以解释一下吗?

提前致谢.

推荐答案

导航项是每个视图控制器.导航栏从当前正在构建其视图的视图控制器的导航项中绘制其内容,该视图对应于导航控制器堆栈顶部的视图控制器.

The navigation item is per view controller. The navigation bar draws its contents from the navigation item of the view controller whose view it's currently framing, which corresponds to the view controller at the top of the navigation controller's stack.

您基本上需要每个视图控制器在其导航项中粘贴一个取消按钮.您可以执行以下任何操作:

You basically need each view controller to stick a cancel button in its navigation item. You can do any of the following:

  • 将代码复制粘贴到所有相关的视图控制器中.
  • 将代码移动到实用函数或类中并调用它.
  • 为所有相关视图控制器创建一个通用超类,以处理为其子类设置取消按钮.

这篇关于向 UINavigationController 中的所有视图控制器添加相同的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆