如图,我们想要设置导航栏背景色为黑色:
首先最常用的就是:[UINavigationBar appearance],可以在继承的NavigationController里边对navigationBar进行统一的设置,
但是直接设置它的背景色backgroundColor:
UINavigationBar *navBar = [UINavigationBar appearance];
navBar.backgroundColor = [UIColor blackColor];
得到却是这样的结果:
正确的做法是设置它的barTintColor:
navBar.barTintColor = [UIColor blackColor];
状态栏默认是黑色,而现在我们需要设置为白色,实现以下方法即可:
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
导航栏背景色设置完毕以后,我们需要设置backBarButtonItem,默认的backBarButtonItem是"<返回",但是我们只想要"<"这个箭头。那么该怎么办呢,首先我们想到的可能就是使用一张带箭头图片,给leftBarButtonItem赋值,为了避免每个页面都设置leftBarButtonItem,我们需要定义一个父类UIViewController,让我们的Controller继承于它。但是这样有个弊端就是当我们使用UITableViewController,又得定义一个父类继承于它。在这里找到一个简便的全局设置方法:
// 设置返回item只保留箭头
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
将文字向上偏移,这样文字就被隐藏了,只剩下"<",符合我们的需求。以下是所有代码:
TSLNavigationController.h
#import <UIKit/UIKit.h>
@interface TSLNavigationController : UINavigationController
@end
TSLNavigationController.m#import "TSLNavigationController.h"
@interface TSLNavigationController ()
@end
@implementation TSLNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
// 设置导航栏属性
UINavigationBar *navBar = [UINavigationBar appearance];
navBar.barTintColor = [UIColor blackColor];
navBar.tintColor = [UIColor whiteColor];
// navBar.backgroundColor = [UIColor blackColor];
// 设置title属性
NSMutableDictionary *titleTextAttrs = [NSMutableDictionary dictionary];
titleTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
titleTextAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
[navBar setTitleTextAttributes:titleTextAttrs];
// 设置返回item只保留箭头
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
}
/**
* 设置状态栏字体颜色
*/
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
未完待续...