Grouped 風格的表格每一組自成一塊圓角卡片,常用於設定頁。以下示範如何用三個方法把它填起來。
@implementation ViewController
- (void)viewDidLoad {
a = [NSArray arrayWithObjects:@"ant", @"alpaca", @"albatross", nil];
b = [NSArray arrayWithObjects:@"badger", @"bat", @"bear", nil];
c = [NSArray arrayWithObjects:@"cat", @"calf", @"cattle", nil];
d = [NSArray arrayWithObjects:@"A", @"B", @"C", nil]; // 各組的標題
[super viewDidLoad];
}
// 設置每組的行數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
// 設置每組的內容
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0) {
cell.textLabel.text = [a objectAtIndex:indexPath.row];
}
if (indexPath.section == 1) {
cell.textLabel.text = [b objectAtIndex:indexPath.row];
}
if (indexPath.section == 2) {
cell.textLabel.text = [c objectAtIndex:indexPath.row];
}
return cell;
}
// 設置組數(section 數量)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [d count];
}
// 取得每組的標題
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
return [d objectAtIndex:section];
}
@end
numberOfSectionsInTableView: 決定有幾組。不實作的話預設為 1。
numberOfRowsInSection: 決定每一組有幾列。注意它帶 section 參數,所以各組行數可以不同。
cellForRowAtIndexPath: 透過 indexPath.section 與 indexPath.row 兩個維度定位到唯一的儲存格。
組標題除了 titleForHeaderInSection,也可以用 viewForHeaderInSection 回傳自訂 view,適合需要放圖示或搜尋框的情況;搭配 heightForHeaderInSection 則能調整標題列的高度。
上面用 if 逐一比對 section 來取資料,section 一多就很難維護。更好的做法是先把三組資料放進一個二維陣列:
NSArray *allSections = @[a, b, c]; // 之後取值就能一行搞定 NSArray *rows = allSections[indexPath.section]; cell.textLabel.text = [rows objectAtIndex:indexPath.row];
這樣 numberOfRowsInSection 也能改成回傳 [allSections[section] count],各組行數不同時同樣適用,完全不必寫條件判斷。