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

UITableView 自定義表格實戰:索引分區、行勾選與樣板定製

編輯:iOS 開發綜合

UITableView 是 iOS 開發裡出場率最高的元件之一,但很多人寫了幾年仍停留在「能顯示數據」的階段。本文用三個循序漸進的實例,把表視圖從基礎用法一路推到完全自訂:先是帶 A~Z 索引的分區列表,接著是能逐行打勾的選擇列表,最後做出類似新聞客戶端的複合樣板。

一、帶索引目錄的表視圖

先看最終效果,右側那條可以拖動定位的字母索引,就是本文第一個目標。

1. 準備數據源

原本想直接讀取通訊裡的姓名,但為了方便在模擬器上反覆除錯,最後改成寫死假數據。字母也只挑了幾個常見的,能說明問題就行。

兩個數組各司其職:sectionTitles 保存每個分區的標題,contentsArray 則是二維結構,每個子數組對應一個分區下的所有姓名。

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
{
    NSArray *sectionTitles;   // 每個分區的標題
    NSArray *contentsArray;   // 每個分區下的行數據
}
@end

/** 準備數據源,在 viewDidLoad 中呼叫 */
- (void)readySource
{
    sectionTitles = [[NSArray alloc] initWithObjects:
                     @"A", @"C", @"F", @"G", @"H", @"M", @"S", @"T", @"X", @"Z", nil];

    contentsArray = [[NSArray alloc] initWithObjects:
                     @[@"阿偉", @"阿姨", @"阿三"],
                     @[@"蔡芯", @"成龍", @"陳鑫", @"陳丹", @"成名"],
                     @[@"芳仔", @"房祖名", @"方大同", @"芳芳", @"范偉"],
                     @[@"郭靖", @"郭美美", @"過兒", @"過山車"],
                     @[@"何仙姑", @"和珅", @"郝歌", @"好人"],
                     @[@"媽媽", @"毛主席"],
                     @[@"孫中山", @"沈冰", @"嬸嬸"],
                     @[@"濤濤", @"淘寶", @"套娃"],
                     @[@"小二", @"夏紫薇", @"許巍", @"許晴"],
                     @[@"周恩來", @"周傑倫", @"張柏芝", @"張大仙"], nil];
}

2. 讓索引真正顯示出來

索引只是兩個 delegate 方法的副產品,並不需要額外建立任何控制項。

// 每個分區的頁眉標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [sectionTitles objectAtIndex:section];
}

// 右側索引列表,回傳的數組元素會直接當成索引文字
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return sectionTitles;
}

3. 點擊索引後的跳轉行為

預設情況下點擊索引就會滾動,但我們通常希望滾動後停在該分區的第一列,因此需要自行實作下面這個方法。

- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index
{
    // 取出該分區的第一列
    NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index];

    // 滾動到目標位置
    [tableView scrollToRowAtIndexPath:selectIndexPath
                    atScrollPosition:UITableViewScrollPositionBottom
                            animated:YES];

    return index;
}

二、可以逐行打勾的表視圖

效果如下,點一下打勾,再點一下取消。

1. 先把輔助樣式歸零

在 cellForRowAtIndexPath 建立 cell 時,把 accessoryType 設為 None,避免系統預設的箭頭混進來。

cell.accessoryType = UITableViewCellAccessoryNone;

2. 在點擊事件裡切換勾選狀態

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        // 已勾選 → 取消
        cell.accessoryType = UITableViewCellAccessoryNone;
    } else {
        // 未勾選 → 打勾
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    // 取消按下時的高亮
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

3. 一個必須正視的坑:cell 重用

做到這裡你會發現,滾動一下列表,某些從沒被點過的列竟然也出現了勾。這不是靈異事件,而是 UITableView 的重用機制在作怪——cell 被回收後,之前設定的 accessoryType 並沒有被清除。

網上常見的應急做法是讓每一列的 reuseIdentifier 都不一樣:

NSString *cellIdentifier = [NSString stringWithFormat:@"cellIdentifier%d%d",
                            indexPath.row, indexPath.section];

這樣確實不會再串台,但代價是徹底放棄了緩衝池,記憶體與效能都吃虞,屬於「亂但可以跑」的方案。正確做法是在 cellForRowAtIndexPath 中,每次都依數據源的實際狀態重設 accessoryType,讓 cell 的外觀完全由數據決定,而不是由上一輪的殘留決定。

三、定製每一列的內容樣板

最後一個案例,做一個類似新聞客戶端的資訊列表:左側縮圖,右側標題、摘要、跟帖數,必要時還要多掛一個「獨家」或「專題」的小標籤。

1. 用 Model 承載數據

先把「一筆新聞」抽象成一個模型類,避免在控制器裡散落十幾個平行數組。

// newsModel.h
#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, NEWSReportType) {
    NEWSReportOrdinary,   // 普通新聞
    NEWSReportExclusive,  // 獨家新聞
    NEWSReportSpecial     // 專題新聞
};

@interface newsModel : NSObject
@property (nonatomic, copy)   NSString      *news_image;    // 配圖
@property (nonatomic, copy)   NSString      *news_title;    // 標題
@property (nonatomic, copy)   NSString      *news_summary;  // 摘要
@property (nonatomic, assign) NSInteger      news_replyNo;  // 跟帖數
@property (nonatomic, assign) NEWSReportType reportType;   // 報道類型
@end

控制器裡只需一個數組:

NSMutableArray *news_MArray;   // 新聞數據源

在 viewDidLoad 中灌入測試數據,這裡用取模運算讓三種報道類型輪流出現:

news_MArray = [[NSMutableArray alloc] init];
for (NSInteger index = 0; index < 10; index++) {
    newsModel *model = [[newsModel alloc] init];
    model.news_image    = [NSString stringWithFormat:@"%d.jpg", index + 1];
    model.news_title    = @"曾在月光之下望煙花";
    model.news_summary  = @"曾共看夕陽漸降下 我怎麼捨得去放下";
    model.news_replyNo  = index + 196;
    model.reportType    = index % 3;

    [news_MArray addObject:model];
}

2. 行數與自訂子視圖

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [news_MArray count];
}

在 cellForRowAtIndexPath 裡,先於 if (cell == nil) 之前取出模型並宣告子視圖:

newsModel *model = [news_MArray objectAtIndex:indexPath.row];

UIImageView *image_view;      // 1. 縮圖
UILabel     *title_label;     // 2. 標題
UILabel     *summary_label;   // 3. 摘要
UILabel     *replyNo_label;   // 4. 跟帖數
UIButton    *extra_view;      // 5. 獨家/專題標記

接著在 if (cell == nil) 內部完成佈局。這裡的關鍵是:一次性建立好的元件才不會隨滾動不斷重建。

// 1. 縮圖
CGRect imageViewF = CGRectMake(5, 5, 85, 65);
image_view = [[UIImageView alloc] initWithFrame:imageViewF];
[cell addSubview:image_view];

// 2. 標題
CGRect titleLabelF = CGRectMake(95, 5, 230, 24);
title_label = [[UILabel alloc] initWithFrame:titleLabelF];
title_label.font = [UIFont systemFontOfSize:16];
[cell addSubview:title_label];

// 3. 摘要
CGRect summaryLabelF = CGRectMake(97, 27, 210, 40);
summary_label = [[UILabel alloc] initWithFrame:summaryLabelF];
summary_label.font = [UIFont systemFontOfSize:12];
summary_label.textColor = [UIColor darkGrayColor];
summary_label.numberOfLines = 2;
[cell addSubview:summary_label];

// 4. 跟帖數
CGRect replyNoLabelF = CGRectMake(210, 45, 95, 24);
replyNo_label = [[UILabel alloc] initWithFrame:replyNoLabelF];
replyNo_label.font = [UIFont systemFontOfSize:12];
replyNo_label.textColor = [UIColor darkGrayColor];
replyNo_label.textAlignment = NSTextAlignmentRight;
[cell addSubview:replyNo_label];

// 5. 類型標記按鈕
CGRect extraViewF = CGRectMake(270, 50, 28, 14);
extra_view = [[UIButton alloc] initWithFrame:extraViewF];
extra_view.titleLabel.font = [UIFont boldSystemFontOfSize:10];
[extra_view setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

if (model.reportType == NEWSReportOrdinary) {
    // 普通新聞:只有跟帖數
    [cell addSubview:replyNo_label];
} else if (model.reportType == NEWSReportSpecial) {
    extra_view.backgroundColor = [UIColor colorWithRed:120.0/255.0
                                                green:170.0/255.0
                                                 blue:245.0/255.0
                                                alpha:1.0];
    [extra_view setTitle:@"獨家" forState:UIControlStateNormal];
    [cell addSubview:extra_view];

    replyNo_label.frame = CGRectMake(170, 45, 95, 24);   // 讓位給標籤
    [cell addSubview:replyNo_label];
} else if (model.reportType == NEWSReportExclusive) {
    extra_view.backgroundColor = [UIColor redColor];
    [extra_view setTitle:@"專題" forState:UIControlStateNormal];
    [cell addSubview:extra_view];
}

最後在 if (cell == nil) 之後填入內容。這一步每次都會執行,是 cell 重用機制下唯一可靠賦值的位置。

[image_view setImage:[UIImage imageNamed:model.news_image]];
title_label.text   = model.news_title;
summary_label.text = model.news_summary;
replyNo_label.text = [NSString stringWithFormat:@"%d 跟帖", model.news_replyNo];

3. 别忘了行高

自訂樣板後,系統無法自動判斷內容該佔多高,必須自己回報:

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

小結

三個案例背後其實是同一條主線:讓視圖的每一個細節都由數據驅動。索引分區靠的是 delegate 的三個回調;行勾選的坑來自重用機制;自訂樣板則要求把「建立」與「賦值」嚴格分開。把這三點想通,UITableView 基本就沒有能難住你的地方了。

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