導航控制器(UINavigationController)是iOS介面中重要的組成部分。一般來說導航控制器要結合TableView來使用,因此我在摸導航控制器前先寫了簡單的TableView(編寫簡單的TableView),下面的例子也是在這個例子基礎上寫的。
本文是參考《iPhone開發基礎教程》寫的,但是這部分教程太囉嗦了。我做了精簡,並拆分成幾個漸進的小例子。第一個例子:
首先,要建立Navigation-based Application:
這樣,xcode會幫你產生一個導航項目的架構。xcode產生的RootViewController實際上是一個UITableViewController,這和編寫簡單的TableView是很類似的。
可以在IB中找到MainWindow.xib,為導航首頁增加標題:
然後,和TableView類似,編寫dataSource,不過不需要通過IB做關聯到file’s owner了。只需要在RootViewController中“填空”即可,標頭檔中:
@interface RootViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource>{
NSArray *dataItems;
在m檔案:
@synthesize dataItems;
…
- (void)viewDidLoad {
[super viewDidLoad];
dataItems= [[NSArray alloc] initWithObjects:@"張三",@"李四",nil];
[super viewDidLoad];
}
…
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [dataItems count];
}
另外,為了做出這個如下的效果:
需要再增加一個函數:
-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryDetailDisclosureButton;
}
這時還沒有牽扯到導航控制器的主要內容,只是做了個TableView而已。
建立詳細內容的控制器,DetailViewController以及對應的xib檔案。需要注意的是要在IB中做控制器到視圖之間的關聯工作。
然後,將DetailViewController設定為RootViewController的成員:
@interface RootViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource>{
NSArray *dataItems;
DetailViewController *detailViewController;
}
之後,回到RootViewController.m檔案中,增加用於處理列表按鈕的函數:
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
if (detailViewController==nil) {
detailViewController=[[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
}
detailViewController.title=@"Detail";
NavTestAppDelegate *delegate=[[UIApplication sharedApplication] delegate];
[delegate.navigationController pushViewController:detailViewController animated:YES];
}
在該函數中初始化了DetailViewController,並且將這個控制器壓棧到控制器棧中。運行程式,就是上面的效果。
這裡要注意,本例中選中條目並不會到詳細頁面,而必須點擊表徵圖按鈕才行。