1.在.m文件中
#import "SGNavigationController.h"
@interface SGNavigationController ()
@end
@implementation SGNavigationController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
+ (void)initialize
{
// 通过appearance对象能修改整个项目中所有UIBarButtonItem的样式
UIBarButtonItem *appearance = [UIBarButtonItem appearance];
// 设置普通状态的文字属性
NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
textAttrs[UITextAttributeTextColor] = [UIColor orangeColor];
textAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:15];
[appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
// 设置高亮状态的文字属性
NSMutableDictionary *highTextAttrs = [NSMutableDictionary dictionary];
highTextAttrs[UITextAttributeTextColor] = [UIColor redColor];
highTextAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:15];
[appearance setTitleTextAttributes:highTextAttrs forState:UIControlStateHighlighted];
// 设置不可用状态(disable)的文字属性
NSMutableDictionary *disableTextAttrs = [NSMutableDictionary dictionary];
disableTextAttrs[UITextAttributeTextColor] = [UIColor lightGrayColor];
disableTextAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:15];
[appearance setTitleTextAttributes:disableTextAttrs forState:UIControlStateDisabled];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (self.viewControllers.count > 0) { // 如果现在push的不是栈底控制器(最先push进来的那个控制器)
viewController.hidesBottomBarWhenPushed = YES;
// 设置导航栏按钮
viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_back" highImageName:@"navigationbar_back_highlighted" target:self action:@selector(back)];
viewController.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_more" highImageName:@"navigationbar_more_highlighted" target:self action:@selector(more)];
}
[super pushViewController:viewController animated:animated];
}
2.其中UIBarButtonItem分类的写法如下
#import "UIBarButtonItem+Extension.h"
@implementation UIBarButtonItem (Extension)
+ (UIBarButtonItem *)itemWithImageName:(NSString *)imageName highImageName:(NSString *)highImageName target:(id)target action:(SEL)action
{
UIButton *button = [[UIButton alloc] init];
[button setBackgroundImage:[UIImage imageWithName:imageName] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageWithName:highImageName] forState:UIControlStateHighlighted];
// 设置按钮的尺寸为背景图片的尺寸
button.size = button.currentBackgroundImage.size;
// 监听按钮点击
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[UIBarButtonItem alloc] initWithCustomView:button];
}
@end
- (void)back
{
#warning 这里用的是self, 因为self就是当前正在使用的导航控制器
[self popViewControllerAnimated:YES];
}
- (void)more
{
[self popToRootViewControllerAnimated:YES];
}
@end