本文转载自:http://www.th7.cn/Program/IOS/201306/139906.shtml
一般导航控制器含有4个对象,UINavigationController、UINavigationBar、UIViewController、UINavigationItem;
NavigationItem存放在UINavigationBar上。由下图我们可以知道一个导航控制器控制着多个视图,一个视图控制器控制一个UINavigationItem
初始化NavigationController
RootViewController *rootViewController = [[RootViewController alloc] init];// UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];// // [navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbar_background.png"] forBarMetrics:UIBarMetricsDefault]; NavigationViewController *navigationController = [[NavigationViewController alloc] initWithRootViewController:rootViewController];
NavigationViewController是继承了UINavigationController
NavigationBar
一个导航控制器控制多个视图,NavigationBar上的leftItem,rightItem,title是由当前的视图控制器控制的,下面看看创建的方法:
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(study)]; self.navigationItem.leftBarButtonItem = leftItem; [leftItem release];
重点看一下,self.navigationItem.leftBarButtonItem这句话,这句话就表明了层次关系,Item是由当前视图控制器的navigationItem控制的,如果写成self.navigationController.navigationItem.leftBarButtonItem 则行不通,这就相当于给每一个视图控制器都加上了leftItem,这违反了我们的初衷!
if([self.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){ [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbar_background.png"] forBarMetrics:UIBarMetricsDefault]; }
这句话只能在ios5以后的版本才能使用,给navigationBar设置背景图片
ToolBar
ToolBar的用法和NavigationBar的用法类似,只不过ToolBar是用数组来管理的,这个很重要,并且默认是隐藏的,要使用的话记得要设置会打开。
UIBarButtonItem *tbarItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(book)]; UIBarButtonItem *tbarItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil]; UIBarButtonItem *tbarItem3 = [[UIBarButtonItem alloc] initWithTitle:@"title" style:(UIBarButtonItemStyleDone) target:self action:nil]; UIBarButtonItem *tbarItem4 = [[UIBarButtonItem alloc] initWithTitle:@"button1" style:(UIBarButtonItemStyleBordered) target:self action:nil]; //设置间隔 UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:self action:nil]; NSArray *itemArray=@[tbarItem,flex,tbarItem1,flex,tbarItem3,flex,tbarItem4]; //默认是隐藏的 [self.navigationController setToolbarHidden:NO animated:YES]; [self setToolbarItems:itemArray];
切记一定要打开来,不然不会显示!
设置navigationBar和tabBar的显示
[self.navigationController setToolbarHidden:NO animated:YES]; [self.navigationController setNavigationBarHidden:NO animated:YES];