在 iOS App 中,UINavigationController、UITabBarController 與 UITableView 是最常見的頁面組織方式。以下整理建立與基本設定方法。
導航控制器適合處理階層式頁面,例如從清單進入詳情頁。
RootViewController *root = [[RootViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:root];
self.window.rootViewController = nav;
可以透過 navigationItem 設定標題與左右按鈕:
self.navigationItem.title = @"首頁";
UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:@"Next"
style:UIBarButtonItemStylePlain
target:self
action:@selector(goNext)];
self.navigationItem.rightBarButtonItem = next;
標籤欄適合切換多個主要功能頁。
UITabBarController *tabBar = [[UITabBarController alloc] init];
tabBar.viewControllers = @[firstViewController, secondViewController];
self.window.rootViewController = tabBar;
若要使用系統圖示,可以建立 UITabBarItem:
self.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:100];
UITableView 常用來顯示列表資料。建立時需設定 dataSource 與 delegate。
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:self.tableView];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = self.items[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"選擇第 %ld 列", (long)indexPath.row);
}
這三個元件經常一起使用。掌握它們的建立方式與基本代理方法,就能完成多數 iOS 列表與導航介面。