//FirstViewController
// 定制化UINavigationBar
- (void)customNavigationBar {
// 按钮被挡住,原因是:navigationbar的透明度默认为YES
// 先取出navigationbar
UINavigationBar *bar =self.navigationController.navigationBar;
// 设置透明度为no
bar.translucent =NO;
/*
如果透明度为yes,下方子视图控制器的(0,0)点在整个屏幕的左上方
如果透明度为no,下方子视图控制器的(0,0)点在导航条的下方,左上方
navigationbar 高度:44
*/
// 设置导航条的title
self.title =@"第一视图";
// 设置背景图
UIImage *img = [UIImageimageNamed:@"header_bg"];
[bar setBackgroundImage:imgforBarMetrics:UIBarMetricsDefault];
/* UIBarMetricsDefault :在视图无论是横屏还是竖屏的情况下,都显示此背景图
UIBarMetricsCompact : 只有在视图是横屏的情况下,显示此背景图
*/
// 因为背景图设置了44高度,所以状态栏没有背景图
// 设置一个高度为64背景图,使状态栏与导航条同色
[bar setBackgroundImage:[UIImageimageNamed:@"header_bg64"]forBarMetrics:UIBarMetricsDefault];
// 设置导航条的背景色 ,如果要显示,背景图不能设置
[bar setBarTintColor:[UIColorgreenColor]];
}
// 在页面触碰事件中,隐藏navigationbar
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.navigationControllersetNavigationBarHidden:YESanimated:YES];
}
//SecondViewController
// 定制本视图的导航项
- (void)customNavigationItem {
// 1. 取出当前视图控制器的导航项
UINavigationItem *item =self.navigationItem;
/* 此item用于显示此视图的标题,以及标题左,右两侧的操作按钮*/
item.title =@"更改后的标题";
/* 此item.title等同于 self.title ,也就是说self.title实际上设置的是导航项的title */
// 带样式的标题
UILabel *lb = [[UILabelalloc] initWithFrame:CGRectMake(0,0, 100,40)];
// 设置lb的属性
lb.text =@"再次更改的标题";
lb.backgroundColor = [UIColororangeColor];
lb.textColor = [UIColorwhiteColor];
// 将lb赋值给item的标题视图
item.titleView = lb;
// 开始自定义设置标题左侧的按钮/按钮组
// 创建左侧按钮
UIBarButtonItem *buttonItem1 = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAddtarget:selfaction:@selector(itemClick:)];// 系统按钮类型
UIBarButtonItem *buttonItem2 = [[UIBarButtonItemalloc] initWithTitle:@"文字"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(item2Click:)];//以文字创建
UIView *uv = [[UIViewalloc] initWithFrame:CGRectMake(0,0, 40,40)];
uv.backgroundColor = [UIColorgrayColor];
UIBarButtonItem *buttonItem3 = [[UIBarButtonItemalloc] initWithCustomView:uv];//自定义视图创建
// 从ios7以后,使用UIImage对象初始化buttonitem,图片不显示。
// [UIBarButtonItem alloc] initWithImage:<#(nullable UIImage *)#> style:<#(UIBarButtonItemStyle)#> target:<#(nullable id)#> action:<#(nullable SEL)#>
// 设置左侧按钮组
item.leftBarButtonItems =@[buttonItem1,buttonItem2,buttonItem3];
// 设置单个左侧按钮
item.leftBarButtonItem = buttonItem1;
// 右侧按钮组,于左侧按钮组设置方式相同,
// 练习,设置右侧按钮组,观察按钮的排放顺序与数组中的顺序是否一致
//返回键
//item.backBarButtonItem
// 在此视图设置返回按钮,自定义样式,是无效的。一般情况下可以在leftbarbutttonitems中设置代替。
// 如果非要使用backBarButtonItem,那么需要在跳转到本视图之前就设置,而不是在本视图设置
}
// 左侧第一个按钮的点击事件
- (void)itemClick:(UIBarButtonItem *)item {
NSLog(@"谁点我了?");
}
// 左侧第二个按钮的点击事件
- (void)item2Click :(UIBarButtonItem *)item {
[self.navigationControllerpopViewControllerAnimated:YES];
}
// 添加视图触碰事件处理,目的:将导航条显示
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.navigationControllersetNavigationBarHidden:NOanimated:YES];
}