如何为所有导航控制器和视图控制器设置自定义导航栏(标题+ titleView)?
我有一个选项卡式应用程序,选项卡中有导航控制器,其中有视图控制器。它们都使用相同的导航控制器导航栏:后退按钮+徽标图像。目前,我将此代码放置在每个视图控制器中:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"Back";
UIImage *headerImage = [UIImage imageNamed:@"Logo.png"];
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:headerImage] autorelease];
}
恕我直言,这不是最好的方法。我正在考虑使用 UIViewController 的类别并覆盖 viewDidLoad 方法,但每个视图控制器都有一些额外的代码要在 viewDidLoad 中执行,所以我想覆盖不是解决方案。还有哪些其他方法?
I have a tabbed application with navigation controllers in tabs and view controller in them. All of them use the same navigation controller navigation bar: back button + logo image. Currently, I'm placing this code in every view controller:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"Back";
UIImage *headerImage = [UIImage imageNamed:@"Logo.png"];
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:headerImage] autorelease];
}
IMHO it's not the best way to do that. I'm thinking about using a category for UIViewController and to override viewDidLoad method, but every view controller has some additional code to execute in viewDidLoad, so I guess overriding is not the solution. What are the other ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建
UIViewController
的子类,MyViewControllerWithBackButtonAndLogo
(您可以想出更好的名称),然后实现viewDidLoad
来设置导航项。让所有视图控制器都继承自这个基类。然后只需确保视图控制器在自己的实现中调用[super viewDidLoad]
即可。另请注意,要设置后退按钮标题,不应更改导航项的
title
属性,而应设置适当的backBarButtonItem
。You could create a subclass of
UIViewController
,MyViewControllerWithBackButtonAndLogo
(you can come up with a better name) then implementviewDidLoad
to set up the navigation item. Make all your view controllers inherit from this base class. Then just make sure the view controllers call[super viewDidLoad]
in their own implementations.Also note that to set the back button title, you should not change the navigation item's
title
property, but set an appropriatebackBarButtonItem
.在正确的架构中,UIViewController(或子类)不应该关心它在哪个上下文中显示(例如,在 UINavigationController、UITabController、模态或非模态中)。考虑使用协调器模式< /a> 其中协调器负责执行此类配置。
例子:
In proper architecture a UIViewController (or sub class) should not care in which context it is displayed (e.g. within a UINavigationController, UITabController, modal or not). Consider using the coordinator pattern where it's the coordinator's responsibility to perform this kind of configuration.
Example: