UITableView 是 iOS 開發中出現頻率最高的元件之一,以下把幾個常用的列舉型別與實務技巧整理在一起。
UITableViewCellSelectionStyle:控制 cell 被點選時的高亮樣式,有 None(不高亮)、Blue(藍底)、Gray(灰底)三種。
UITableViewCellAccessoryType:控制 cell 右側的附屬檢視。None 不顯示;DisclosureIndicator 是灰色箭頭、不可點擊;DetailDisclosureButton 是藍色按鈕加箭頭、可點擊;Checkmark 則是勾選標記。
UITableViewCellSeparatorStyle:控制分隔線樣式,None 為不顯示,SingleLine 為單線,若要改顏色則另外設定 separatorColor。
點擊 cell 進入下一頁後再返回,列表往往會被滾回最頂端,體驗很差。解法是記下點擊的 indexPath,在 viewWillAppear: 時重新選中該列:
NSIndexPath *ip = [NSIndexPath indexPathForRow:row inSection:section]; [topicsTable selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionNone];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
實作 willSelectRowAtIndexPath: 並回傳 nil,就能攔下特定列:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([indexPath row] == 0) return nil; // 第一列不可選
return indexPath;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return ([indexPath row] != 0); // 第一列不允許刪除
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// 從資料來源移除資料,再 reload 或 deleteRowsAtIndexPaths
}
}
實作以下方法即可在列表右側出現 A、B、C 的索引條,適合聯絡人這類大量資料:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return @[@"A", @"B", @"C", @"Z"];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return @"Section Title";
}
注意:原方法名若拼成 titleForHeardInSection 是不會被呼叫的,正確拼法是 titleForHeaderInSection,這也是新手常踩的雷。