UITableView 是 iOS 最常被使用的元件之一。下面用一份可運行的範例,把建立、資料源、代理與 cell 重用機制一次講清楚。
先在 .h 中宣告屬性:
@property (nonatomic, strong) UITableView *table;
接著在實作中建立並設定:
self.table = [[UITableView alloc] initWithFrame:self.bounds
style:UITableViewStylePlain];
self.table.rowHeight = 260.0; // 列高
self.table.separatorColor = [UIColor redColor]; // 分隔線顏色
self.table.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched; // 分隔線樣式
[self addSubview:self.table];
指定每一個 section 有幾列:
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 5;
}
產生每一列的 cell。這裡要重點說明重用機制:如果資料多達數百筆,每次都配置新的 UITableViewCell 會造成大量記憶體配置。UIKit 內部以 MutableSet 實作重用池,滑出畫面的 cell 會被回收,滑回來時直接取用。
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cell_id = @"a"; // 重用識別碼
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
if (nil == cell) { // 池中沒有才重新配置
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cell_id];
}
cell.textLabel.text = @"今天很開心";
cell.detailTextLabel.text = @"可以回家了弟弟";
return cell;
}
補充說明:在 iOS 6 之後,也可以改用 dequeueReusableCellWithIdentifier:forIndexPath:,系統會自動負責配置,不必自己寫 if (nil == cell) 判斷。
其他資料源方法:
// 共有幾個 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.groupArray.count;
}
// 每個 section 的標題
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
NSArray *a = @[@"李", @"張"];
return a[section];
}
// 每個 section 的尾註
- (NSString *)tableView:(UITableView *)tableView
titleForFooterInSection:(NSInteger)section
{
NSArray *a = @[@"李的版權", @"張的版權"];
return a[section];
}
// 點擊某一列
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Hello, World");
}
// 逐列自訂高度,優於全域 rowHeight
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
return 100;
return 60.0;
}
// 區塊標題與尾註高度
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section { return 50; }
- (CGFloat)tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section { return 50; }
// 用任意 UIView 子類取代區塊標題
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.backgroundColor = [UIColor orangeColor];
return button;
}
// 用任意 UIView 子類取代區塊尾註
- (UIView *)tableView:(UITableView *)tableView
viewForFooterInSection:(NSInteger)section
{
UIImageView *img = [[UIImageView alloc]
initWithImage:[UIImage imageNamed:@"DSC_8898.JPG"]];
return img;
}
最後記得在 viewDidLoad 中設定 self.table.delegate 與 self.table.dataSource,否則所有回呼都不會觸發——這也是初學者最常漏掉的一步。