一般導航控制器含有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];