先來看幾個常配合 UITableView 使用的列舉:
// 選取樣式
typedef enum {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray
} UITableViewCellSelectionStyle;
// cell 右側按鈕樣式
typedef enum {
UITableViewCellAccessoryNone, // 不顯示
UITableViewCellAccessoryDisclosureIndicator, // 一般箭頭
UITableViewCellAccessoryDetailDisclosureButton, // 藍色按鈕含箭頭
UITableViewCellAccessoryCheckmark // 勾選記號
} UITableViewCellAccessoryType;
// 分隔線樣式
typedef enum {
UITableViewCellSeparatorStyleNone,
UITableViewCellSeparatorStyleSingleLine
} UITableViewCellSeparatorStyle;
以下整理幾個實用技巧:
1. 點擊某個 cell 進入另一個 view 後,返回時若想停在點擊前的位置,可先記住並重新選中該列:
NSIndexPath *ip = [NSIndexPath indexPathForRow:row inSection:section];
[TopicsTable selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionNone];
2. 選中 cell 的回呼,並讓選取後的高亮即刻消失:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
3. 若不想讓使用者點擊某一列,可在 willSelectRowAtIndexPath 中回傳 nil:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = [indexPath row];
if (row == 0) return nil; // 阻止選中第一行
return indexPath;
}
4. 控制滑動 cell 是否出現刪除按鈕:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
}
5. 處理編輯狀態:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}
6. 在右側加入索引表:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
}
7. 回傳各 section 的標題內容:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
}