如何在 UINavigationController 中为所有 viewController 添加 UiBarButtonItem
我想知道是否可以直接将按钮添加到导航控制器中,或者我必须从推入导航控制器的所有 viewController
添加按钮?
示例:我有 3 个 UIViewController(VC1、VC2 和 VC3),我可以将这些元素推送到 NavigationController (NC) 中。如果我需要为 VC1 添加一个按钮作为右侧导航项,我可以在 VC1 的 viewDidLoad 中编写:
UIBarButtonItem *settingsBtn = [[UIBarButtonItem alloc]initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings)];
self.navigationItem.rightBarButtonItem = settingsBtn;
如果我也需要在 NC 上为 VC2 和 VC3 添加此按钮,我必须在 VC2 和 VC3 中添加此代码也并在 VC1、VC2 和 VC3 中指定方法“设置”
是否可以以共享方式添加此按钮?如何将设置方法定义为共享方法?
I wonder if it's possible to add a button directly into a navigation controller
, or I have to add button from all viewController
pushed into navigation Controller
?
Example: I have 3 UIViewController
(VC1, VC2 and VC3) and I can push this elements in a NavigationController (NC). If I need to add a button as right navigation item for VC1 I can write in viewDidLoad
of VC1 :
UIBarButtonItem *settingsBtn = [[UIBarButtonItem alloc]initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings)];
self.navigationItem.rightBarButtonItem = settingsBtn;
If I need this button on NC also for VC2 and VC3 I have to add this code in VC2 and VC3 too and specify method "settings" in VC1,VC2 and VC3
Is it possible to add this button in a shared way? And how can I define settings method as shared method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
成为 UINavigationController 的委托。
Become a delegate of the UINavigationController.
实现此目的的一种方法是拥有一个 UIViewController 派生自的父类。在父类中,您可以在
viewDidLoad
中设置按钮。在您的子类中,您将在viewDidLoad
方法中执行[super viewDidLoad];
。希望这有帮助!
One way to do this is to have a parent class that your
UIViewController
s derive from. In the parent class, you can set the button in, say,viewDidLoad
. In your children classes, you would do[super viewDidLoad];
in yourviewDidLoad
method.Hope this helps!