您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UITableView 入門(一):純程式碼建表、Cell 樣式與互動

編輯:iOS 開發綜合

UITableView 是 iOS 上最常見的列表元件。這個系列會拆成幾篇來談,涵蓋範圍如下:

1. 純程式碼建立 UITableView
2. Cell 的樣式、點擊事件與重用機制
3. 下拉刷新與上拉載入
4. 自訂 Cell

本篇先處理前兩項的基礎部分:建立表、Cell 樣式、Cell 重用、點擊事件與左滑按鈕。

一、建立 UITableView

首先在 ViewController 的類別宣告後面加上 UITableViewDelegate 與 UITableViewDataSource。

Swift:

Objective-C:

UITableView 有兩種樣式:Grouped 與 Plain。

Grouped:

Plain:

依需求挑一種即可,以下兩種都會示範。

1. 建立並加入畫面

Swift:

// style 可選 .Grouped 或 .Plain,這裡以 Grouped 為例
let tableView = UITableView(
    frame: CGRectMake(0, 20,
                      self.view.frame.size.width,
                      self.view.frame.size.height - 20),
    style: .Grouped)

tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)

Objective-C:

// style 可選 UITableViewStyleGrouped 或 UITableViewStylePlain
UITableView *tableView = [[UITableView alloc]
    initWithFrame:CGRectMake(0, 20,
                             self.view.frame.size.width,
                             self.view.frame.size.height - 20)
            style:UITableViewStyleGrouped];

tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];

2. 提供資料來源

Grouped 樣式還需實作 section 數量:

Swift:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 6
}

Objective-C:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

以下兩個方法則是 Grouped 與 Plain 都必須實作的,負責決定行數與每列的內容。

Swift:

// 每個 section 有幾列
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

// 設定每一列
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // 用同一個 ID 從重用池取 cell
    let cellID = "cellID"
    var cell = tableView.dequeueReusableCellWithIdentifier(cellID)

    // 池裡沒有就新建一個,樣式為 Value2
    if cell == nil {
        cell = UITableViewCell(style: .Value2, reuseIdentifier: cellID)
    }

    cell?.textLabel?.text = "這是第\(indexPath.row)個cell"
    cell?.detailTextLabel?.text = "副標題"
    return cell!
}

Objective-C:

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"cellID";
    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleValue2
          reuseIdentifier:cellID];
    }

    cell.textLabel.text =
        [NSString stringWithFormat:@"這是第%li個cell", (long)indexPath.row];
    cell.detailTextLabel.text = @"副標題";
    return cell;
}

執行後,一個基礎列表就出現在畫面上了:

這裡順帶一提 cell 的四種內建樣式,可依版面需求挑選:

——— 以下是 delegate 方法篇 ———

二、delegate 方法介紹

1. 樣式相關

a. 設定 section 的 header 與 footer 文字

Swift:

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "header-\(section)"
}

func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    return "footer-\(section)"
}

Objective-C:

- (NSString *)tableView:(UITableView *)tableView
    titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"header-%li", (long)section];
}

- (NSString *)tableView:(UITableView *)tableView
    titleForFooterInSection:(NSInteger)section {
    return [NSString stringWithFormat:@"footer-%li", (long)section];
}

b. 設定 header、footer 與 cell 的高度

Swift:

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 10
}

func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 10
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 80
}

Objective-C:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

c. 設定 cell 文字縮排

Swift:

func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
    return 10
}

Objective-C:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 10;
}

d. 自訂 header 與 footer

把 header/footer 換成自訂的 view。注意:一旦採用自訂 view,前面用文字設定的方法就失效了,文字必須自己畫在 view 上。

Swift:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRectMake(0, 0, 100, 10))
    headerView.backgroundColor = UIColor.redColor()
    return headerView
}

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRectMake(0, 0, 100, 10))
    footerView.backgroundColor = UIColor.orangeColor()
    return footerView
}

Objective-C:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
    headerView.backgroundColor = [UIColor redColor];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
    footerView.backgroundColor = [UIColor orangeColor];
    return footerView;
}

自訂 header/footer 的效果:

2. 操作相關

a. 點選 cell

Swift:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("選中了第\(indexPath.row)個cell")
}

Objective-C:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"選中了第%li個cell", (long)indexPath.row);
}

b. 左滑刪除

先來看系統預設的左滑按鈕。

Swift:

// 是否允許左滑
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

// 預設左滑按鈕的文字
func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
    return "按鈕鈕鈕"
}

// 點擊左滑按鈕時觸發
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    print("點擊左滑出現的按鈕時觸發")
}

// 左滑結束時呼叫(只對預設按鈕有效)
func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) {
    print("左滑結束")
}

Objective-C:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return true;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"按鈕鈕鈕";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"點擊左滑出現的按鈕時觸發");
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"左滑結束");
}

效果:

若要自訂左滑出現的按鈕與對應事件,改用 editActionsForRowAtIndexPath。

Swift:

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    // 第一個按鈕
    let cellActionA = UITableViewRowAction(style: .Default, title: "按鈕-1") { _, _ in
        // 在這裡寫點擊後的處理
    }
    cellActionA.backgroundColor = UIColor.greenColor()

    // 第二個按鈕
    let cellActionB = UITableViewRowAction(style: .Default, title: "按鈕-2") { _, _ in
        // 在這裡寫點擊後的處理
    }

    // 注意:即使只有一個按鈕,也必須回傳陣列
    return [cellActionA, cellActionB]
}

Objective-C:

- (nullable NSArray<UITableViewRowAction *> *)
tableView:(UITableView *)tableView
editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {

    // 第一個按鈕
    UITableViewRowAction *cellActionA =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                       title:@"按鈕-1"
                                     handler:^(UITableViewRowAction *action,
                                               NSIndexPath *indexPath) {
        NSLog(@"點擊了 按鈕-1");
    }];
    cellActionA.backgroundColor = [UIColor greenColor];

    // 第二個按鈕
    UITableViewRowAction *cellActionB =
    [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                       title:@"按鈕-2"
                                     handler:^(UITableViewRowAction *action,
                                               NSIndexPath *indexPath) {
        // 在這裡寫點擊後的處理
    }];

    // 回傳的是按鈕陣列,即使只有一個也要用陣列包裝
    return @[cellActionA, cellActionB];
}

效果:

以上就是 UITableView 的基礎操作。下一篇會接著談下拉刷新、上拉載入與自訂 Cell——那才是列表在真實專案裡最常遇到的場景。

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