1.創建
通過xib創建
通過代碼創建
一個UINavigationcontroller包括 navigation bar,可選的navigation toolbar,RootViewController.
2.導航棧
有四個方法
- 例如,想推進一個新的viewcontroller,到導航棧中,代碼:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[[tableView cellForRowAtIndexPath:indexPath] setSelected:NO animated:YES];//1.
DetailsViewController *detailsViewController = [[DetailsViewController alloc]
initWithNibName:@"DetailsViewController" bundle:nil];
[self.navigationController pushViewController:detailsViewController];
[detailsViewController release];
}
- 這裏有兩個需要注意的地方
- 1.進入下一個頁面的時候,table中的選擇行要取消。
- 2.記得release要push的controller.因爲導航棧是retain的。
3.配置Navigation bar
可能大家想直接訪問navigationcontroller 的navigation bar。但是通常我們不這樣做。而是維護每個viewcontroller的 navigation item。
這裏不要將navigation item 與 navigation bar 混淆,navigation item不是UIView的子類。它是一個用來更新navigtion bar的存儲信息的類。
還是上代碼說明:
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[[tableView cellForRowAtIndexPath:indexPath] setSelected:NO animated:YES];
Person *person;
// Some code that sets person based on the particular cell that was selected
DetailsViewController *detailsViewController = [[DetailsViewController alloc]
initWithNibName:@"DetailsViewController" bundle:nil];
detailsViewController.navigationItem.title = person.name;
[self.navigationController pushViewController:detailsViewController];
[detailsViewController release];
}
detailsViewController.navigationItem.title = person.name;這句話的意思就是把二級界面的導航標題設置成person.name
要注意兩點:1.我們並沒有直接操作navigation bar 2.在push 新的controller之前設置標題
當新的detailcontroller被push後,UINavigationController會自動更新navigation bar。
4.返回按鈕
默認情況下,當你將一個新的viewcontroller推入棧的時候,返回按鈕將顯示前一個頁面的controller的 navigation item的title。
如果想定製返回按鈕的標題還有事件的話,可以用以下代碼。
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
注意,這裏的self是第一級的view controller。這樣的話第二級的頁面將顯示“Back”
5.左右按鈕
navigation item還有兩個屬性leftBarButtonItem rightBarButtonItem。
一般leftBarButtonItem只出現在RootviewController中使用,因爲其他頁面一般都顯示一個返回按鈕。
UIBarButtonItem *settingsButton = [[UIBarButtonItem alloc] initWithTitle:@"Settings"
style:UIBarButtonItemStylePlain target:self action:@selector(handleSettings)];
self.navigationItem.rightBarButtonItem = settingsButton;
[settingsButton release];
這會在右側添加一個“Setting”的按鈕,並觸發handleSetting事件。
6.在首頁隱藏Navigation Bar
在RootViewController.m中實現如下:
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES animated:YES]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.navigationController setNavigationBarHidden:NO animated:YES]; }