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

UITableView 設計全攻略:樣式、Cell 複用與增刪改移的完整實作

編輯:iOS 開發綜合

UITableView 的 API 設計得相當克制,但正是這種克制讓它能適應幾乎所有列表場景。本文從元件結構講起,一路做到增刪改移與批量操作,把列表開發的完整套路走一遍。

一、UITableView 基礎

表視圖是一個可滾動的多行單列列表,每一行都是一個 UITableViewCell 物件。它提供兩種風格:

typedef NS_ENUM(NSInteger, UITableViewStyle) {
    UITableViewStylePlain,     // 通欄式,頁眉懸浮
    UITableViewStyleGrouped    // 分組式,圓角卡片
};

表視圖還可以加上索引,就是通訊錄右側那條字母列,每個索引項對應一個分區標題:

最簡單的形態是選擇列表,可限制單選或多選(即上圖右側)。此外還能自訂頁眉與頁腳:

二、UITableViewCell 的四種內建樣式

系統會快取可見範圍內的行,透過實作 cellForRowAtIndexPath: 來填充資料。Cell 有四種預設樣式:

UITableViewCellStyleDefault,    // 一個 imageView + 一個 textLabel
UITableViewCellStyleValue1,     // textLabel + detailLabel(右對齊、藍色)
UITableViewCellStyleValue2,     // textLabel(藍色右對齊)+ detailLabel(緊鄰其右)
UITableViewCellStyleSubtitle    // textLabel + detailLabel(在下方,字體較小)

三、建立一個簡單的 TableView

先看效果:

1. 為什麼要獨立成一個類

建立 Single View Application 並命名為 tableView,接著繼承 UITableView 建立一個 general_table_view 類。把所有 table 相關的實現集中在此,好處是當 ViewController 代碼量膨脹,或同一個 table 需要在多處使用時,可以直接複用。

2. 宣告屬性與代理

// general_table_view.h
@interface general_table_view : UITableView

@property (nonatomic, assign) CGRect        tableViewFrame;   // 位置與尺寸
@property (nonatomic, copy)   NSMutableArray *textLabel_MArray;   // 各行主標題
@property (nonatomic, copy)   NSMutableArray *images_MArray;      // 各行圖片
@property (nonatomic, copy)   NSMutableArray *subtitle_MArray;    // 各行副標題

@end
// general_table_view.m
@interface general_table_view () <UITableViewDataSource, UITableViewDelegate>
@end

在 initWithFrame 中綁定代理,並實作 frame 的 setter:

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.delegate   = self;
        self.dataSource = self;
    }
    return self;
}

- (void)setTableViewFrame:(CGRect)tableViewFrame
{
    self.frame = tableViewFrame;
}

3. 兩個必須實作的方法

// 每個分區的行數
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [_textLabel_MArray count];
}

// 每一行的內容
- (UITableViewCell *)tableView:(UITableView *)
         tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 標識符是複用機制的比對依據
    static NSString *cellIdentifier = @"cellIdentifier";

    // 先從佇列中嘗試取回可重用的 cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    // 佇列為空才建立新的
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    // 賦值必須放在 if 之外,否則重用時會顯示錯誤內容
    cell.textLabel.text = [_textLabel_MArray objectAtIndex:indexPath.row];

    return cell;
}

這裡有個至關重要的觀念:標識符是系統用來比對「這個 cell 能不能重複使用」的唯一依據。同一種外觀的行必須共用同一個標識符,否則緩衝池形同虛設;不同外觀的行則必須用不同標識符。而賦值永遠寫在 if 之外,因為那一段每次呼叫都會執行。

4. 其他輔助方法

// 分區數量,預設 1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 頁眉
- (NSString *)tableView:(UITableView *)tableView
 titleForHeaderInSection:(NSInteger)section
{
    return @"頁眉";
}

// 頁腳
- (NSString *)tableView:(UITableView *)tableView
 titleForFooterInSection:(NSInteger)section
{
    return @"頁腳";
}

5. 在控制器中使用

#import "general_table_view.h"

@interface ViewController ()
{
    general_table_view *table;
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    table = [[general_table_view alloc] initWithFrame:CGRectMake(0, 20, 320,
                                                  self.view.frame.size.height - 20)
                                                style:UITableViewStylePlain];

    table.textLabel_MArray = [[NSMutableArray alloc] initWithObjects:
        @"南京市", @"南通市", @"淮安市", @"鎮江市", @"揚州市", @"常州市", nil];

    [self.view addSubview:table];
}

把 style 改成 UITableViewStyleGrouped,就能得到第二張分組樣式的效果。

四、為每一行加上圖片

在 viewDidLoad 中,addSubview 之前先準備圖片陣列:

NSMutableArray *images = [NSMutableArray array];

for (NSInteger index = 0; index < [table.textLabel_MArray count]; index++) {
    UIImage *image = [UIImage imageNamed:@"2"];
    [images addObject:image];
}

table.images_MArray = [[NSMutableArray alloc] initWithArray:images];

然後在 cellForRowAtIndexPath 中賦值:

cell.textLabel.text   = [_textLabel_MArray objectAtIndex:indexPath.row];
cell.imageView.image  = [_images_MArray objectAtIndex:indexPath.row];

五、切換 Cell 樣式

準備副標題資料:

NSMutableArray *subtitle = [NSMutableArray array];

for (NSInteger index = 0; index < [table.textLabel_MArray count]; index++) {
    UIImage *image = [UIImage imageNamed:@"2"];
    NSString *detail = [NSString stringWithFormat:@"detail text %d", index + 1];

    [images   addObject:image];
    [subtitle addObject:detail];
}

table.subtitle_MArray = [[NSMutableArray alloc] initWithArray:subtitle];

把初始化 Cell 時的 UITableViewCellStyleDefault 換成其他三種樣式,並補上:

cell.detailTextLabel.text = [_subtitle_MArray objectAtIndex:indexPath.row];

效果如下:

六、行的各類操作

1. 選中行

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"您點擊了第 %d 分區第 %d 行", indexPath.section, indexPath.row);

    // 需要取消高亮時取消下面這行的註解
    // [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

2. 刪除單行

先開放編輯能力:

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

左滑就會出現刪除按鈕:

按鈕文字預設是 delete,可以改:

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

點擊刪除後的處理:

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 先刪資料源
    [self.dataArray removeObjectAtIndex:indexPath.row];

    // 再刪畫面
    [tableView deleteRowsAtIndexPaths:@[indexPath]
                   withRowAnimation:UITableViewRowAnimationFade];
}

順序不能顛倒。資料源與 UI 必須同步變更,否則會出現畫面與數據不一致的崩潰。

3. 插入行

把插入與刪除都做成按鈕觸發,點擊後進入編輯模式:

// viewDidLoad 中設定導航欄按鈕
NSArray *leftBarButtons = @[self.addButton, self.deleteBarButtonItem];
self.navigationItem.leftBarButtonItems = leftBarButtons;

// 宣告一個變量記錄目前的編輯意圖
UITableViewCellEditingStyle selectEditingStyle;
// 更新導航欄按鈕狀態
- (void)updateBarButtons
{
    if (self.tableView.editing == YES) {
        self.navigationItem.rightBarButtonItem = self.doneBarButtonItem;
    }
}

- (IBAction)addButtonClicked:(id)sender
{
    selectEditingStyle = UITableViewCellEditingStyleInsert;
    [self.tableView setEditing:YES animated:YES];
    [self updateBarButtons];
}

- (IBAction)deleteButtonClicked:(id)sender
{
    selectEditingStyle = UITableViewCellEditingStyleDelete;
    [self.tableView setEditing:YES animated:YES];
    [self updateBarButtons];
}
// 編輯模式下依意圖分派
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return selectEditingStyle;
}

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.dataArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath]
                       withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        [self.dataArray insertObject:@"new iPhone" atIndex:indexPath.row];
        [self.tableView insertRowsAtIndexPaths:@[indexPath]
                            withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (IBAction)doneButtonClicked:(id)sender
{
    [self.tableView setEditing:NO animated:YES];
    [self updateBarButtons];
}

4. 移動行

進入編輯模式後,Cell 右側會出現拖曳控點:

- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
      toIndexPath:(NSIndexPath *)destinationIndexPath
{
    // 本質上就是數組中兩個元素交換位置
    id object = [self.dataArray objectAtIndex:sourceIndexPath.row];

    [self.dataArray removeObjectAtIndex:sourceIndexPath.row];
    [self.dataArray insertObject:object atIndex:destinationIndexPath.row];
}

5. 批量刪除

目標是點擊編輯後,右上角變「取消」、左上角變「刪除」,並即時顯示已選數量。

self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
- (void)updateBarButtons
{
    // 進入多選模式
    if (self.tableView.allowsSelectionDuringEditing == YES) {
        [self updateDeleteButtonTitle];

        self.navigationItem.leftBarButtonItems = nil;
        self.navigationItem.leftBarButtonItem  = self.multiDeleteBarButton;
        self.navigationItem.rightBarButtonItem = self.cancelBarButtonItem;
        return;
    }

    if (self.tableView.editing == YES) {
        self.navigationItem.rightBarButtonItem = self.doneBarButtonItem;
    } else {
        NSArray *leftBarButtons = @[self.addButton, self.deleteBarButtonItem];
        self.navigationItem.leftBarButtonItems = leftBarButtons;
        self.navigationItem.rightBarButtonItem = self.editBarButtonItem;
    }
}

// 依選中數量動態改按鈕標題
- (void)updateDeleteButtonTitle
{
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];

    BOOL allItemsAreSelected = selectedRows.count == self.dataArray.count;
    BOOL noItemsAreSelected  = selectedRows.count == 0;

    if (allItemsAreSelected || noItemsAreSelected) {
        self.multiDeleteBarButton.title = @"刪除全部";
    } else {
        self.multiDeleteBarButton.title =
            [NSString stringWithFormat:@"刪除 (%d)", selectedRows.count];
    }
}

在選中與取消選中的回調中呼叫標題更新:

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateDeleteButtonTitle];
}

- (void)tableView:(UITableView *)tableView
didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateDeleteButtonTitle];
}
- (IBAction)editButtonClicked:(id)sender
{
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    [self.tableView setEditing:YES animated:YES];
    [self updateBarButtons];
}

- (IBAction)multiDeleteClicked:(id)sender
{
    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];
    BOOL deleteSpecificRows = selectedRows.count > 0;

    if (deleteSpecificRows) {
        // 把所選索引集合起來一次刪除
        NSMutableIndexSet *indicesOfItemsToDelete = [NSMutableIndexSet new];

        for (NSIndexPath *selectionIndex in selectedRows) {
            [indicesOfItemsToDelete addIndex:selectionIndex.row];
        }

        [self.dataArray removeObjectsAtIndexes:indicesOfItemsToDelete];
        [self.tableView deleteRowsAtIndexPaths:selectedRows
                            withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        // 未選任何行視為刪除全部
        [self.dataArray removeAllObjects];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
                    withRowAnimation:UITableViewRowAnimationAutomatic];
    }

    // 收尾:退出編輯與多選狀態,重設導航欄
    [self.tableView setEditing:NO animated:YES];
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    [self updateBarButtons];
}

整理一下心法

整套 UITableView 的用法,可以收斂成四條:

  1. 數據源是唯一真相。所有增刪改移都先動數據,再通知 UI,順序不可逆。
  2. 標識符決定複用效率。同外觀共用標識符,賦值寫在 if 之外。
  3. 樣式選擇決定代碼量。能用內建的四種 CellStyle 解決就不要自訂子視圖。
  4. 批量操作靠三個開關。allowsSelectionDuringEditing、allowsMultipleSelectionDuringEditing 與 setEditing: 的組合,覆蓋了絕大多數多選場景。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved