您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 導航控制器、標籤欄與表視圖建立教學

編輯:iOS 相關資訊

在 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 列表與導航介面。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved