UINavigationBar 和 UINavigationItem的属性设置

时间:2022-06-10 04:16:30
 #import "RootViewController.h"

 @interface RootViewController ()

 @end

 @implementation RootViewController

 - (void)viewDidLoad {
[super viewDidLoad]; self.view.backgroundColor = [UIColor orangeColor]; // 布局导航控制器
[self initLayout]; } - (void)initLayout { // 导航控制器的显示和隐藏
self.navigationController.navigationBarHidden = NO; #pragma mark - UINavigationBar(导航条)
// 设置导航条是否开启半透明效果
// ios7.0之后,半透明效果默认是打开的,当半透明效果开启时,self.view以屏幕左上角为坐标原点,关闭时,导航条左下角为坐标原点。
self.navigationController.navigationBar.translucent = NO; // UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
// view.backgroundColor = [UIColor cyanColor];
// [self.view addSubview:view]; // 修改导航条颜色
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
// self.navigationController.navigationBar.backgroundColor = [UIColor redColor]; // 修改背景颜色不能完成修改导航条颜色 // 设置导航元素的颜色(item上按钮的颜色)
self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; // 导航栏样式
self.navigationController.navigationBar.barStyle = UIBarStyleBlack; // 系统只有两种样式 // 设置导航条标题
self.title = @"根视图"; #pragma mark - navigationTtem属性
self.navigationItem.title = @"根视图"; // 也可以设置导航条标题 // 左按钮
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"左按钮" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)]; // 右按钮
// self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(rightItemClick:)]; // self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"222.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick:)]; // 某一边添加多个按钮,可以用rightBarButtonItems来添加多个,先创建多个按钮,再用数组的形式添加
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightItemClick:)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(rightItemClick:)]; self.navigationItem.rightBarButtonItems = @[item1, item2]; // 标题视图
UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"卫庄", @"盖聂"]];
//segment.frame = CGRectMake(0, 0, 100, 30); // 位置是固定的,设置frame并没有用
// 修改标题视图
self.navigationItem.titleView = segment; } // 实现方法
- (void)leftItemAction:(UIBarButtonItem *)sender { NSLog(@"左按钮");
} - (void)rightItemClick:(UIBarButtonItem *)sender { NSLog(@"右按钮");
}