如何自定义UINavigationBar

问题描述:

我在自定义UINavigationBar中挣扎。我想定制的原因是因为在不同的视图控制器中可能会发生相同的操作。作为例子,我张贴了一些图片。如何自定义UINavigationBar

Navigation Bar - 1Navigation Bar - 2Navigation Bar - 3

正如你可以从上面的图片看。我想你明白我的意思。我一直在努力寻找,但我没有得到我想要的答案。此外,我已经尝试使用UIView来实现这一点,它的工作原理,但我不认为这是做到这一点的正确方法。因此,我需要你们的帮助,让我走向正确的道路。 :) :) 谢谢。

您可以像这样将自定义标题视图设置为导航栏。

//To hide default back button 
self.navigationItem.hidesBackButton=YES; 

//Title View for Navigation 
UIView *navTitle1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; 
[navTitle1 setBackgroundColor:[UIColor lightGrayColor]]; 

//Left View button and separator 
UIButton *backBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)]; 
[backBarButton setTitle:@"Back" forState:UIControlStateNormal]; 

UIView *ttlview1 = [[UIView alloc] initWithFrame:CGRectMake(51, 0, 1, 44)]; 
[ttlview1 setBackgroundColor:[UIColor darkGrayColor]]; 


//Center view with two buttons and seprator for them 
UIView *middleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 121, 44)]; 
[middleView setBackgroundColor:[UIColor clearColor]]; 
[middleView setCenter:navTitle1.center]; 

UIButton *postBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)]; 
[postBarButton setTitle:@"Post" forState:UIControlStateNormal]; 

UIView *ttlview2 = [[UIView alloc] initWithFrame:CGRectMake(middleView.frame.size.width/2, 0, 1, 44)]; 
[ttlview2 setBackgroundColor:[UIColor darkGrayColor]]; 

UIButton *memeBarButton = [[UIButton alloc] initWithFrame:CGRectMake((middleView.frame.size.width/2)+1, 0, 60, 44)]; 
[memeBarButton setTitle:@"Meme" forState:UIControlStateNormal]; 

[middleView addSubview:ttlview2]; 
[middleView addSubview:postBarButton]; 
[middleView addSubview:memeBarButton]; 

//Right button with seprator before that 
UIView *ttlview3 = [[UIView alloc]  initWithFrame:CGRectMake(self.view.frame.size.width-71, 0, 1, 44)]; 
[ttlview3 setBackgroundColor:[UIColor darkGrayColor]]; 

有关更多详细信息,请参阅THIS

+0

这是的UIBarButtonItem我之前做了什么。这是正确的,而不是自定义。 – tan

+0

我认为,这是方式,你可以做高级别的定制,默认导航栏不提供通过本机功能和按钮直接做这种定制。 –

您可以从2次创建2个自定义的UIBarButtonItem,使用本文件:

从苹果文档: 使用指定的自定义视图的新项目。

- (id)initWithCustomView:(UIView *)customView 

参数customView:表示项目A自定义视图。 返回值具有指定属性的新初始化项目。

  • 左栏项目:1视图包含3个按钮:项目,Kiara Paradize,艺术家印象。

  • 右栏项目:1视图包含4个按钮:注册|登录(用户登录时的配置文件按钮)|汉堡菜单

然后:

  • self.navigationItem.leftBarButtonItem =从左 自定义视图
  • self.navigationItem.rightBarButtonItem =的UIBarButtonItem从右自定义视图