新建指定风格的控制器如下:
编辑NavViewController.h如下:
// // NavViewController.h // 作业整理 // // Created by apple on 15/9/14. // Copyright (c) 2015年 LiuXun. All rights reserved. // #import <UIKit/UIKit.h> @interface NavViewController : UIViewController { UIButton *btnLeft; UIButton *btnRight; } -(void)setLeftItem:(BOOL) left setRightItem:(BOOL) RIght; -(void) afterPressLeft; -(void)afterPressRight; @end
// // NavViewController.m // 作业整理 // // Created by apple on 15/9/14. // Copyright (c) 2015年 LiuXun. All rights reserved. // #import "NavViewController.h" @interface NavViewController () @end @implementation NavViewController - (void)viewDidLoad { [super viewDidLoad]; btnLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; [btnLeft setImage:[UIImage imageNamed:@"-register_nav_icon_back"] forState:UIControlStateNormal]; [btnLeft setImage:[UIImage imageNamed:@"-register_nav_icon_back_press"] forState:UIControlStateHighlighted]; [btnLeft addTarget:self action:@selector(afterPressLeft) forControlEvents:UIControlEventTouchUpInside]; btnRight= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; [btnRight setImage:[UIImage imageNamed:@"wanshanziliao_icon_affirm"] forState:UIControlStateNormal]; [btnRight setImage:[UIImage imageNamed:@"wanshanziliao_icon_affirm_press"] forState:UIControlStateHighlighted]; [btnRight addTarget:self action:@selector(afterPressRight) forControlEvents:UIControlEventTouchUpInside]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)setLeftItem:(BOOL) left setRightItem:(BOOL) RIght { if (left) { self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnLeft]; } if (RIght) { self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight]; } } -(void) afterPressLeft { NSLog(@"++++"); } -(void)afterPressRight { NSLog(@"-------"); } @end
当子控制器调用
-(void)setLeftItem:(BOOL) left setRightItem:(BOOL) RIght方法后根据左右的 BOOL判断显不显示左右指定格式的按钮
如果要为导航栏的左右按钮添加点击事件只需重写父类的
-(void) afterPressLeft
<pre name="code" class="objc">-(void)afterPressRight
方法即可:
例如以下的导航栏都是继承此控制器