在controller的- (void)viewDidLoad方法中通过如下方式自定义导航栏左侧的按钮
UIImage* backImage = [UIImage imageNamed:@"back1.png"];
UIImage* backImage2 = [UIImage imageNamed:@"back2.png"];
UIButton* backButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, backImage.size.width, backImage.size.height)];
[backButton setBackgroundImage:backImage forState:UIControlStateNormal];
[backButton setBackgroundImage:backImage2 forState:UIControlStateHighlighted];
[backButton addTarget:self action:@selector(doClickBackAction:) forControlEvents:UIControlEventTouchUpInside];
backButton.tag = 102;
[self.navigationController.view addSubview:backButton];
通过这种方式可以很好的自定义按钮视图。但是这样导航栏并不知道我们有自己的返回按钮,但这个视图被push进入时就会出现一个很丑的默认返回按钮,文字为上一个视图的名字。因此需要在- (void)viewDidLoad方法中加入这样一句代码,告诉其隐藏默认的返回按钮。
//push进时隐藏默认的返回按钮
[self.navigationItem setHidesBackButton:YES animated:NO];
另外,同样是因为NavigationBar并不知道我们自己的返回按钮的存在,它会将标题title从最左侧开始,与我们的按钮重叠在一起,因此我们可以通过用一个Label自定义标题视图来解决。在- (void)viewDidLoad方法中加入如下的代码。
//因为返回按钮是采用添加子视图的方式,直接设置标题的话会与返回按钮重叠,因此标题通过使用UILabel控件自定义
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 11, 220, 20)];
titleLabel.backgroundColor = global_bg_color;
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont systemFontOfSize:18.];
titleLabel.tag = 103;
titleLabel.textAlignment = NSTextAlignmentCenter;
[self.navigationController.view addSubview:titleLabel];
在- (void)viewWillAppear:(BOOL)animated方法中可以通过这样的方式设置导航栏标题。
UILabel *titleLabel = (UILabel *)[self.navigationController.view viewWithTag:103];
titleLabel.text = @“title”;
NSLog(@"title label %@", titleLabel);
另外,要记住推出视图时要移除返回按钮和标题视图。
- (void)viewWillDisappear:(BOOL)animated {
//视图推出时删除返回按钮和标题,否则会带到文章列表页
UIView *backButton = [self.navigationController.view viewWithTag:102];
[backButton removeFromSuperview];
UILabel *titleLabel = (UILabel *)[self.navigationController.view viewWithTag:103];
[titleLabel removeFromSuperview];
}