UINavigationBar的常见用法总结

在项目中,我们经常需要去定制导航栏及状态栏的显示样式,或者显示/隐藏。下面总结一下常见的用法。

设置导航栏的title

有两种办法:

  1. 通过navigationItem修改
    self.navigationItem.title = @"学习导航栏中";
  2. 通过ViewController修改
    self.title = @"学习导航栏中"

设置导航栏的背景颜色

self.navigationController.navigationBar.barTintColor = [UIColor greenColor];
效果:

bar_background_color.png

设置导航栏标题的字体,颜色

NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor cyanColor], NSFontAttributeName: [UIFont systemFontOfSize: 30]};
[self.navigationController.navigationBar setTitleTextAttributes: attributes];

效果:


title_font_and_color.png

设置导航栏背景图片

这里为了简单起见,用颜色绘制出图片。

UIImage *image1 = [UIImage imageWithColor: [UIColor redColor]];
UIImage *image2 = [UIImage imageWithColor: [UIColor blueColor]];
UINavigationBar *navBar = self.navigationController.navigationBar;
[navBar setBackgroundImage: image1 forBarMetrics: UIBarMetricsDefault];
[navBar setBackgroundImage: image2 forBarMetrics: UIBarMetricsCompact];

设定背景图片时,要指定图片适用的场合。UIBarMetricsDefault用于竖屏时,UIBarMetricsCompact用于横屏时。

设置导航栏为透明效果

导航栏默认就是半透的效果,但如果想实现alpha值从0到1的任意透明度,可用下面的代码。

CGFloat alphaValue = 0.2; //可设为0到1之间的任意值
UINavigationBar *navBar = self.navigationController.navigationBar;
[navBar setBackgroundImage: [UIImage imageWithColor: [UIColor colorWithRed: 0 green: 0 blue: 1 alpha: alphaValue]] forBarMetrics: UIBarMetricsDefault];

如果需要在拖动ScrollView的过程中,修改导航栏的透明度,就要用到上面的代码。

隐藏导航栏下方的分隔线

导航栏下方,默认带有一条灰色的分隔线。如果想要隐藏,需要同时设置和backgroundImage和shadowImage两个属性。如果不设置backgroundImage,那么即使设了shadowImage,也不会生效。

[self.navigationController.navigationBar setBackgroundImage: [UIImage new] forBarMetrics: UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];

修改导航栏下方的分隔线颜色

既然为shadowImage赋值为[UIImage New]时,可以隐藏分隔线,那么我们也可以根据此原理,来修改分隔线的颜色。

[self.navigationController.navigationBar setBackgroundImage: [UIImage new] forBarMetrics: UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage imageWithColor: [UIColor redColor]];

在导航栏的标题上方增加一个提示文字

self.navigationItem.prompt = @"Navigation prompts appear at the top.";
UIImage *image1 = [UIImage imageWithColor: [UIColor yellowColor]];
UIImage *image2 = [UIImage imageWithColor: [UIColor purpleColor]];
UINavigationBar *navBar = self.navigationController.navigationBar;
[navBar setBackgroundImage: image1 forBarMetrics: UIBarMetricsDefaultPrompt];
[navBar setBackgroundImage: image2 forBarMetrics: UIBarMetricsCompactPrompt];
prompt.png

在设置了prompt的情况下,导航栏的高度会变大。相对应的,新增了两种BarMetrics:UIBarMetricsDefaultPrompt和UIBarMetricsCompactPrompt,分别对应于竖屏和横屏。

设置导航栏左右两侧的按钮

UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle: @"返回" style: UIBarButtonItemStylePlain target: self action: @selector(onBack)];
UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithTitle: @"关闭" style: UIBarButtonItemStylePlain target: self action: @selector(onClose)];
self.navigationItem.leftBarButtonItems = @[backItem, closeItem];
    
UIBarButtonItem *right1 = [[UIBarButtonItem alloc] initWithTitle: @"右1" style: UIBarButtonItemStylePlain target: nil action: nil];
UIBarButtonItem *right2 = [[UIBarButtonItem alloc] initWithTitle: @"右2" style: UIBarButtonItemStylePlain target: nil action: nil];
self.navigationItem.rightBarButtonItems = @[right1, right2];

设置导航栏的标题为视图

UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:@[@"男生",@"女生", @"全部"]];
[segControl setSelectedSegmentIndex:0];
self.navigationItem.titleView = segControl;

设置导航栏的渲染颜色

UINavigationBar的tintColor属性,可以用来修改返回按钮,以及左右两侧的按钮的文字的颜色。

self.title = NSStringFromClass([self class]);
self.navigationController.navigationBar.tintColor = [UIColor yellowColor];
    
UIBarButtonItem *right1 = [[UIBarButtonItem alloc] initWithTitle: @"右1" style: UIBarButtonItemStylePlain target: nil action: nil];
UIBarButtonItem *right2 = [[UIBarButtonItem alloc] initWithTitle: @"右2" style: UIBarButtonItemStylePlain target: nil action: nil];
self.navigationItem.rightBarButtonItems = @[right1, right2];
tintColor.png

隐藏导航栏

self.navigationController.navigationBarHidden = YES;

修改返回按钮

方法1:修改UINavigationItem的leftBarButtonItem(s)

UIImage *leftButtonIcon = [[UIImage imageNamed:@"titlebar_back_normal"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:leftButtonIcon
                                                                style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(goToBack)];
    
UIBarButtonItem *negaSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negaSpacer.width = -20.f;
self.navigationItem.leftBarButtonItems = @[negaSpacer, leftButton];
backbutton.png

这种方法的好处是,可以设定返回按钮的响应函数;但是也会带来一个问题,就是从左边屏幕的边缘,向右滑动时,不能返回上级界面了,也就是右滑手势失效了。解决办法是,在push一个ViewController之后,将self.navigationController.interactivePopGestureRecognizer.delegate 设为nil.

TestBackButton *vc = [TestBackButton new];
[self.navigationController pushViewController: vc animated: YES];
self.navigationController.interactivePopGestureRecognizer.delegate = nil;

方法2:设置返回按钮的图片,将标题置为空字符串

UIImage *backButtonBackgroundImage = [UIImage imageNamed:@"Menu"];
    
id appearance = [UIBarButtonItem appearanceWhenContainedIn:[CustomBackButtonNavController class], nil];
[appearance setBackButtonBackgroundImage:backButtonBackgroundImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
// Provide an empty backBarButton to hide the 'Back' text present by
// default in the back button.
//
// NOTE: You do not need to provide a target or action.  These are set
//       by the navigation bar.
// NOTE: Setting the title of this bar button item to ' ' (space) works
//       around a bug in iOS 7.0.x where the background image would be
//       horizontally compressed if the back button title is empty.
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:nil action:NULL];
self.navigationItem.backBarButtonItem = backBarButton;

这种方法不会影响右滑手势,但是返回按钮的响应函数是系统内置的,无法修改,即使你指定了target和action,也不会被调用。
另外需要注意的是,假设视图控制器A设置了backBarButtonItem,那么只有当从A跳转到B时,才会用到这些设置。这和leftBarButtonItem(s)和rightBarButtonItem(s)是不同的。

设置状态栏样式及是否隐藏

在iOS7及以后的版本中,苹果推荐使用基于ViewController的方案,UIApplication类中的setStatusBarStyle, setStatusBarHidden等方法将被废弃。通过在Info.plist中添加UIViewControllerBasedStatusBarAppearance,并将其置设为YES,APP就声明自己使用基于ViewController的方案。


InfoPlist.png

在自己的视图控制器类中,重写两个方法:

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

但是要注意的是,如果视图是嵌入在容器类的视图控制器内,如UINavigationController,那么框架会去调用容器视图控制器的上述两个方法。所以需要自定义一个UINavigationController的子类,重写上述的两个方法。

- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.topViewController.preferredStatusBarStyle;
}

- (BOOL)prefersStatusBarHidden {
    return self.topViewController.prefersStatusBarHidden;
}

结束语

个人水平有限,如果文中有错误之处,欢迎指正。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容