在设置标题栏时常常遇到修改标题、修改返回按钮标题、增加一些按钮等需求,实现过程中一般会把UINavigationController、UINavigationBar、navigationItem及self.navigationController.navigationItem之间概念会混淆。因此写了下面的博客
概念描述
UINavigationController:是一个ViewController,导航栏控制器,其通过栈来直接控制了其下的viewController。可通过此设置全局导航栏属性。如导航栏背景或title颜色等。子视图会继承这些属性,具体见下面“初始化UINavigationController”
UINavigationBar:是一个View,NavigaitonBar就是导航栏,位于屏幕的上方,管理整个NavigationController的navigationItem,即类似navigationController一样提供了一个栈来管理item。初始化UINavigationController
ViewController *vc = [[ViewController alloc]init];
UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:vc];
//此处可设置背景颜色及文字颜色
方法一:
[navi.navigationBar setBarTintColor:[UIColor colorWithRed:20/255.0 green:155/255.0 blue:213/255.0 alpha:1.0]];
[navi.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
方法二:
//设置NavigationBar背景颜色
[[UINavigationBar appearance] setBarTintColor:[UIColor redColor]];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
self.window.rootViewController = navi;
[self.window makeKeyAndVisible];
UIBarButtonItem *returnButtonItem = [[UIBarButtonItem alloc] init];
returnButtonItem.title = @"";
self.navigationItem.backBarButtonItem = returnButtonItem;
此方法需要在父视图中,pushViewConTroller调用之前设置。
self.navigationItem.leftBarButtonItem = leftItem;
UIImage *backButtonImage = [[UIImage imageNamed:@"image1"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//将返回按钮的文字position设置不在屏幕上显示
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
设置标题
self.title = @”…”;
UIBarButtonItem *removeButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(remove)];
[self.navigationItem setRightBarButtonItem:removeButton];
参考文献: