一.如何创建一个导航控制器
如上图:创建了一个导航栏控制器并作为窗体的根控制器
二.导航栏控制器的重要属性
viewControllers 是一个盛放 push过的视图控制器的 数组 viewControllers viewControllers 里面的元素 是按照 push先后顺序 存放的
三.导航栏控制器的重要方法
1. pushViewController: animated:
把一个页面 推到另外一个页面(切换视图控制器) -> 切换的时候 会把 第二个视图控制 添加 到viewControllers里面
2. popViewControllerAnimated:
返回到上一个页面 -> 把viewControllers里面当前的视图控制器移除
3.popToViewController:指定的视图控制器 animated:
返回到某一个视图控制器 -> 移除viewControllers里面指定的视图控制器与当前视图控制器之间元素都会移除
4.popToRootViewControllerAnimated:
返回跟视图控制器(导航控制器里面的)-> 移除除了根视图控制器的其他所有元素
四.常用的属性
1.设置图层的颜色
对象名.navigationBar.tintColor = [UIColor brownColor];
2.设置导航栏的背景图片
[对象名.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar"] forBarMetrics:UIBarMetricsDefault];
NSForegroundColorAttributeName 设置文本字体颜色的key
[对象名.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:30]}];
5.设置所有导航栏图层颜色
[UINavigationBar appearance] 可以找到所有的导航栏
[UINavigationBar appearance].tintColor = [UIColor brownColor];
(1)设置带有标题的按钮
初始化一个带标题的按钮
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"你好" style:UIBarButtonItemStylePlain target:self action:@selector(show)];
self.navigationItem.leftBarButtonItem = leftButton;
(2)设置左侧图片按钮
UIBarButtonItem *leftImage = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"panda"] style:UIBarButtonItemStylePlain target:self action:@selector(show)];
self.navigationItem.leftBarButtonItem = leftImage;
(3)设置自定义按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 10, 40, 40);
[button setTitle:@"哈哈" forState:UIControlStateNormal];
设置背景图片 还可以显示文本 若直接设置图片会遮挡文字
[button setBackgroundImage:[UIImage imageNamed:@"panda"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
需要这个方法来接收自定义按钮
UIBarButtonItem *leftWithCustom = [[UIBarButtonItem alloc]initWithCustomView:button];
把接收的按钮赋值
self.navigationItem.leftBarButtonItem = leftWithCustom;
4.设置标题视图
初始化一个按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
设置按钮的frame
button.frame = CGRectMake(10, 10, 40, 40);
设置按钮的标题
[button setTitle:@"哈哈" forState:UIControlStateNormal];
设置按钮的背景图片
[button setBackgroundImage:[UIImage imageNamed:@"panda"] forState:UIControlStateNormal];
给按钮增加触发事件
[button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
把按钮给标题视图
self.navigationItem.titleView = button;
5.给导航栏设置返回按钮
注意:必须有下一个页面 才会有返回按钮 才可以设置
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"<<" style:UIBarButtonItemStylePlain target:self action:@selector(show)];
// 这个方法可以是供上面调用的
- (void)show{
NSArray *colorList = @[[UIColor redColor],[UIColor brownColor],[UIColor cyanColor]];
self.view.backgroundColor = colorList[arc4random()%colorList.count];
}