UINavigationBar是用于实现管理层级关系内容的组件,直接继承自UIView。通常用在UINavgationController类中,用于管理和显示UINavgationController的subViewController , 同时UINavgationBar也可以单独使用,添加至任何的UIView中。UINavigationBar比较重要的属性为,左侧按钮,中间的标题,以及右侧按钮。
1、UINavigationBar的创建
UINavigationBar * navigationBarDefault = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 40, 320, 40)];
2、设置UIBarStyle
typedef enum {
UIBarStyleDefault = 0, //对应一个蓝色渐变背景
UIBarStyleBlack = 1, //对应一个不透明的褐色背景样式。
UIBarStyleBlackOpaque = 1, // Deprecated 等用于UIBarStyleBlack样式,但规定为弃用类型
UIBarStyleBlackTranslucent = 2, // Deprecated 等用于barStyle设置为UIBarStyleBlack,同时指定translucent属性为YES,规定为弃用类型。
} UIBarStyle;
navigationBarDefault.barStyle = UIBarStyleDefault;
3、添加UINavigationItem
UINavgationBar虽然直接继承于UIView,但其本身并不是同其它UIView一样通过addSubview去添加内容,比较特殊的是,需要通过navgation item类向其补充指定的 内容,包括按钮和标题。究其原因是在设计上UINavgationBar是通过维护一个UINavgationItem对象栈来实现管理具有层级关系的视图内容。通过
- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated;
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated; // Returns the item that was popped.
- (void)setItems:(NSArray *)items animated:(BOOL)animated; // If animated is YES, then simulate a push or pop depending on whether the new top item was previously in the stack.
UINavigationItem * defaultItem = [[UINavigationItem alloc]initWithTitle:@"默认导航栏"];
[navigationBarDefault setItems:[NSArray arrayWithObjects:defaultItem, nil]];
4、设置左右button
通过设置UINavigation的左右button来设置UINavigationBar的左右button
UIBarButtonItem * leftDefaultButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:nil];
defaultItem.leftBarButtonItem = leftDefaultButton;
UIBarButtonItem * rightDefaultButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];
defaultItem.rightBarButtonItem = rightDefaultButton;
5、其他重要属性
UINavgationBar的topItem指定了当前navgation bar显示的内容,topItem为栈顶元素,假如当前navgation bar维护了n个items,那么topItem的索引为n-1
UINavgationBar的backItem保存了topItem的下一个item,即索引为n-2的item。如果当前只有一个item,那么该属性为nil,而不是与topItem指向相同的item