UITableView 是 iOS 中最常用的清單元件之一。本文從建立表格開始,完整說明資料源(DataSource)與代理(Delegate)的常用方法。
先在 .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 靠 MutableSet 來實作重用,避免資料多時建立大量 cell 而浪費記憶體:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 建立重用識別碼
static NSString *cell_id = @"a";
// 從池中嘗試取得可重用的 cell
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;
}
section 數量、標題與尾注:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.groupArray.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSArray *a = @[@"李", @"張"];
return a[section];
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
NSArray *a = @[@"李的版權", @"張的版權"];
return a[section];
}
點擊 cell 時觸發的事件:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Hello, World");
}
自訂每一列的高度(可針對特定列做變化):
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
return 100;
}
return 60.0;
}
自訂 header 與 footer 的高度,以及放入自訂的 UIView 子類。header 可以是任何 UIView 的子類,例如按鈕;footer 則可以放圖片:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.backgroundColor = [UIColor orangeColor];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"DSC_8898.JPG"]];
return img;
}
掌握 DataSource 負責「內容」、Delegate 負責「互動與外觀」這兩個分工,就能靈活打造各種樣式的清單介面。