自定义导航控制器
在实际的ios项目开发中,通常使用自定义的导航控制器,而不是系统默认的UINavigationController,这样做的好处是,只要在自定义的导航控制器中对导航栏设置了通用的主题,就不需要在每个视图控制器中对该主题进行设置,节省了代码量,又保证了导航栏的一致性。
首先对故事板设置自定义导航栏控制器:
代码示例:
#import "LXXNavigationController.h"
@interface LXXNavigationController ()
@end
@implementationLXXNavigationController
- (void)viewDidLoad {
[super viewDidLoad];
//首先取出设置主题的对象
UINavigationBar *navBar = [UINavigationBar appearance];
//注意这是设置导航栏背景的颜色,即导航栏所覆盖的底层的颜色。而不是导航栏本身的颜色。
[navBar setBackgroundColor:[UIColor greenColor]];
//这才是设置导航栏本身的颜色
[navBar setBarTintColor:[UIColor orangeColor]];
//如果要对导航栏设置背景图片
[navBar setBackgroundImage:[UIImage imageNamed:@"NavBar64"] forBarMetrics:UIBarMetricsDefault];
//设置阴影(IOS7 later)
NSShadow *shadow = [[NSShadow alloc]init];
shadow.shadowColor = [UIColor blackColor];
shadow.shadowOffset = CGSizeMake(2, 2);
//设置标题
NSDictionary *barTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor greenColor],NSForegroundColorAttributeName,
[UIFont fontWithName:@"Verdana" size:17.0f],NSFontAttributeName,
shadow, NSShadowAttributeName,
nil];
[navBar setTitleTextAttributes:barTitleTextAttributes];
//设置首页默认的标题
[[self.viewControllers lastObject] setTitle:@"Lotheve"];
}
#pragma mark 重写push方法
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
[super pushViewController:viewController animated:YES];
//如果导航栏左按钮不存在,则对其进行设置
if (viewController.navigationItem.leftBarButtonItem == nil) {
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@" 返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
}
//设置默认的导航栏标题
viewController.title = @"Test";
}
#pragma mark 设置按钮动作
- (void)backAction:(UIBarButtonItem *)sender
{
[self popViewControllerAnimated:YES];
}
#pragma mark 设置状态栏类型
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
#pragma mark 设置横竖屏切换
//开关(是否允许切换)
- (BOOL)shouldAutorotate
{
return YES;
}
//支持的方向
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
@end
效果展示