| 自定义的导航控制器继承自系统的导航控制器(UINavigationController), 然后在写自己的代码.
.h 文件
#import <UIKit/UIKit.h>
@interface YYNavController : UINavigationController
@end
.m 文件
#import "YYNavController.h"
@interface YYNavController ()
@end
@implementation YYNavController
/**
当第一次来到这个类的时候调用一次
在这里做一些类的初始化设置
*/
+ (void)initialize{
// 设置导航栏背景图片 通过appearance设置那几个类的NAV的背景图
UINavigationBar *bar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[self class]]];
[bar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.childViewControllers.count > 0) { // 这个判断一定要加, 不然会有问题
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
backBtn.size = CGSizeMake(100, 30);
// 设置文字颜色
[backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
// 设置标题
[backBtn setTitle:@"返回" forState:UIControlStateNormal];
// 设置图片
[backBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[backBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateHighlighted];
// 添加点击事件
[backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
//设置内容靠左显示(重点)
backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// 设置内边距(重点)
[backBtn setContentEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
viewController.hidesBottomBarWhenPushed = true; // 隐藏底部tabBar
}
[super pushViewController:viewController animated:animated];
}
- (void)backAction{
[self popViewControllerAnimated:true];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
注意:1.使用前添加头文件
2.图片名称没有补全