本文主要介绍一下UINavigationBar的简单使用和一些属性、方法。下面通过代码来讲解。新建项目,使得主窗口的根视图是导航栏控制器,这里导航栏控制器的主视图是HXMainViewController。
导航栏高度默认:44。自iOS7.0之后,控制器的状态栏也是导航栏的一部分,即导航栏部分44 + 20,
首先来设置导航栏上的左右按钮
// 在导航条上添加左右按钮
// 左边
UIBarButtonItem *hahaItem = [[UIBarButtonItem alloc] initWithTitle:@"哈哈" style:UIBarButtonItemStylePlain target:nil action:nil];
UIBarButtonItem *xixiItem = [[UIBarButtonItem alloc] initWithTitle:@"嘻嘻" style:UIBarButtonItemStyleDone target:nil action:nil];
// 设置单个按钮
// self.navigationItem.leftBarButtonItem = hahaItem;
// 设置多个按钮
self.navigationItem.leftBarButtonItems = @[hahaItem, xixiItem];
// 右边
UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:nil action:nil];
// 设置单个按钮
// self.navigationItem.rightBarButtonItem = addItem;
// 设置多个按钮
self.navigationItem.rightBarButtonItems = @[addItem, searchItem];
以上设置的导航栏按钮都是利用系统自带的按钮设置,下面设置自定义的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.backgroundColor = [UIColor redColor];
[button setTitle:@"自定义按钮" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 44);
// 当自定义导航栏上的子控件时,控件的位置设置就没有效果
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customItem;
// 当自定义导航栏左侧或右侧按钮时,位置可能不是自己想要的,可以进行如下设置(两种方法)
// 1.设置固定宽度的FixedSpace样式的item
// UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
// <span style="color:#FF0000;">spaceItem.width = -10;</span>// 让FixedSpace样式的item宽度为-10,这样就可以让customItem向左靠近
// self.navigationItem.leftBarButtonItems = @[spaceItem, customItem];
// 2.设置控件的内容边距
button.contentEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0);
// 也可以设置成向左靠近的效果,右边的控件也可以同样设置导航栏不仅可以设置左右控件,还可以设置中间控件(标题),利用titleView属性
// 设置头部标题
// self.title = @"Main";// 可同时设置头部标题和tabBar(标签按钮)上的标题
self.navigationItem.title = @"Main";
// 设置标题控件
self.navigationItem.titleView = [UIButton buttonWithType:UIButtonTypeContactAdd];设置导航栏自身的一些属性
// 设置导航栏背景颜色
// self.navigationController.navigationBar.tintColor = [UIColor redColor];// iOS7.0之前有效,iOS7.0之后没有效
self.navigationController.navigationBar.barTintColor = [UIColor clearColor];// iOS7.0之后有效
// 隐藏导航栏
self.navigationController.navigationBar.hidden = YES;
// self.navigationController.navigationBarHidden = YES;
下面对UINavigationBar上的结构做一个简单的图例,如下:

本文详细介绍了UINavigationBar的基本使用方法及其属性、方法的应用。包括导航栏的高度设置、左右按钮的添加方式,自定义按钮的实现及位置调整技巧,以及导航栏背景颜色设置和隐藏等操作。
1071

被折叠的 条评论
为什么被折叠?



