1.首先说明什么是导航控制器
导航控制器是通过栈的形式来管理子控制器的(先进后出)。
显示在导航控制器上得view永远是栈顶控制器的view。
一个导航控制器只有一个导航条,也就是说所有的控制器公用一个导航条。
在任意一个导航栏的子控制器里修改导航栏的属性同样会显示在其他的子控制器里。
所以在任意控制器里修改导航栏属性之后,都要在当前的控制器的viewWillDisappear里重新修改回来。
2.创建一个导航控制器
ViewController *vcRoot = [[ViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vcRoot];
self.window.rootViewController = nav;
3.导航栏常用属性
self.title = @"导航栏";
self.navigationItem.title = @"导航栏";//这两个都是设置导航栏的标题,但建议使用第二种
self.navigationController.navigationBar.translucent = NO;//导航栏透明度,默认为YES:透明
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;//导航栏的风格颜色
self.navigationController.navigationBar.tintColor = [UIColor redColor];//设置按钮的颜色
self.navigationController.navigationBar.barTintColor = [UIColor grayColor];//导航栏的背景颜色
//自定义导航栏标题字体颜色,大小
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName:[UIFont systemFontOfSize:16]};
//导航栏的隐藏
self.navigationController.navigationBarHidden = NO;
self.navigationController.navigationBar.hidden = NO;
4.导航栏创建按钮的几种方式
//自定义Title创建 导航栏按钮项
UIBarButtonItem *next = [[UIBarButtonItem alloc]initWithTitle:@"下一级" style:UIBarButtonItemStyleDone target:self action:@selector(pressbtn1)];
//用系统风格创建 导航栏按钮项
UIBarButtonItem *btn1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(pressbtn)];
//使用图片创建 导航栏按钮项
//1.创建一个 btn
UIButton *img = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//2.设置 btn 的 image
[img setImage:[UIImage imageNamed:@"返回-1"] forState:UIControlStateNormal];
//3.再设置 btn.frame
img.frame = CGRectMake(0, 0, 36, 36);
//4.给 btn 添加事件
[img addTarget:self action:@selector(pressbtn) forControlEvents:UIControlEventTouchUpInside];
//5.将 btn 赋给 UIBarButtonItem
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc]initWithCustomView:img];//这也是自定义导航栏按钮的方法,只要是UIView 和继承自 UIView 就可以放进去,很灵活
//占位的 UIBarButtonItem 使用 UIBarButtonSystemItemFixedSpace 将 width 设为负数,
//一般用于左右移左右导航栏按钮,或者 leftBarButtonItems 中多个按钮的占位
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spaceItem.width = -15;
UIBarButtonItem *spaceItem1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spaceItem.width = 15;
//导航栏按钮项元素数组赋值
self.navigationItem.leftBarButtonItems = @[spaceItem,btn2,spaceItem1,btn1];
//导航栏按钮项元素单个赋值
self.navigationItem.rightBarButtonItem = next;
5.导航栏的推入推出
-(void)pushViewController {
//创建要推入的控制器
ViewController *vc = [[ViewController alloc]init];
//将控制器推入,入栈
[self.navigationController pushViewController:vc animated:YES];
}
-(void)popViewController {
//推出当前控制器,出栈,会显示出栈后下一个栈顶元素
[self.navigationController popViewControllerAnimated:YES];
//直接出栈到根控制器,全出栈只剩栈底的根控制器
[self.navigationController popToRootViewControllerAnimated:YES];
}