多视图应用程序中,我们常常使用到自定义UINavigationBar来完成导航条的设置。
1.获取导航条
UINavigationBar *navBar = self.navigationController.navigationBar;
2.设置导航条样式(使用系统自带样式)
[navBar setBarStyle:UIBarStyleDefault];
分别有如下几种样式:
typedef NS_ENUM(NSInteger, UIBarStyle) {
UIBarStyleDefault = 0,//默认样式
UIBarStyleBlack = 1,//黑色
UIBarStyleBlackOpaque = 1, // Deprecated.黑色不透明 Use UIBarStyleBlack
UIBarStyleBlackTranslucent = 2, //Deprecated. 黑色透明 Use UIBarStyleBlack and set the translucent property to YES
};
所以,我们使用UIBarStyleDefaul
t和UIBarStyleBlack
来定义UINavigationBar样式,并且用setTranslucent:
方法来设置透明与否。
从字面我们就能了解这4种样式的大概意思:
但是往往系统的并不能满足我们的需求,我们需要自定义导航条样式,这个时候如果我们的给出的设计图有很多导航条的重复使用,封装会让我们的代码量大大减小,来看一个栗子:
"BaseViewController.m"中实现如下代码
//BaseViewController继承于UIViewController
-(void)setCommonNav{
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
UINavigationBar * navBar = self.navigationController.navigationBar;
//去掉导航栏的小线
[navBar setTintColor:[UIColor whiteColor]];
// //设置UINavigationBar背景颜色(不包括状态栏,不适用)
// navBar.backgroundColor = RGB_MAINBLUE;
//设置UINavigationBar背景图片(横竖屏都OK)
[navBar setBackgroundImage:[UIImage imageNamed:@"toubu.png"] forBarMetrics:UIBarMetricsDefault];
//左侧UIBarButtonItem:自定义
UIBarButtonItem * leftBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"箭头.png"] style:UIBarButtonItemStylePlain target:self action:@selector(clickLeftBtn:)];
self.navigationItem.leftBarButtonItem = leftBtn;
//微调 leftBarButtonItem位置
leftBtn.imageInsets = UIEdgeInsetsMake(0.5, 5, 0, 0);
//右侧 UIBarButtonItem:
UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(pressRightBtn:)];
self.navigationItem.rightBarButtonItem =rightBtn;
}
-(void)clickLeftBtn:(UIBarButtonItem *)sender{
NSLog(@"点击左侧按钮");
[self.navigationController popViewControllerAnimated:YES];
}
-(void)pressRightBtn:(UIBarButtonItem *)sender{
NSLog(@"点击右侧按钮");
}
其他的跟BaseViewController有相同UINavigationBar的VC继承于BaseViewController即可。
@interface HomeViewController : BaseViewController
================我是一只程序媛=================