UITableView 大概是用戶最多的元件,也是 delegate 方法最多的元件。這篇把常用需求依序做過一遍,從最基礎的資料來源,一路到搜尋、增刪、拖曳與分組索引。
控制器需遵守三個協定:
@interface RootViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate>
@property (retain, nonatomic) UITableView *mTableView;
@property (retain, nonatomic) NSArray *Arr;
@end
初始化表格並設定代理:
self.Arr = [UIFont familyNames];
self.mTableView = [[UITableView alloc] initWithFrame:self.view.frame
style:UITableViewStylePlain];
self.mTableView.sectionHeaderHeight = 40;
self.mTableView.dataSource = self;
self.mTableView.delegate = self;
// 每個 section 的行數
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.Arr count];
}
// 每一列的繪製
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifer = @"identifer";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:identifer];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:identifer];
}
NSString *str = [self.Arr objectAtIndex:[indexPath row]];
cell.textLabel.text = str;
cell.textLabel.font = [UIFont fontWithName:str size:18];
cell.detailTextLabel.text = @"detailText";
cell.imageView.image = [UIImage imageNamed:@"Default-568h@2x"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
return cell;
}
// 選取某列
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSString *str = [NSString stringWithFormat:@"你選中了第%d行", row];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"ActionSheet"
delegate:self cancelButtonTitle:@"確認" destructiveButtonTitle:str
otherButtonTitles:nil, nil];
[sheet showInView:self.view];
[self.mTableView deselectRowAtIndexPath:indexPath animated:YES];
}
// 列高
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 88;
}
// 頁首高度
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
return 40;
}
自訂 cell 的做法是建立一個 MyCell 類別,放入需要的 Label 與 Button,然後在 cellForRowAtIndexPath: 中轉型:
MYCell *cell = (MYCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
if (nil == cell) {
cell = [[MYCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:identifer];
}
cell.NameLable.text = @"name";
cell.ColorLable.text = @"color";
這裡的轉型是最容易漏掉的一步,忘了它就會在執行時拿到錯的型別。
此時控制器改為遵守 <UITableViewDataSource, UISearchBarDelegate>,並用兩個陣列:一個存原始資料,一個存篩選結果。
self.mSeachBar = [[UISearchBar alloc]
initWithFrame:CGRectMake(0, 0, self.mTableView.frame.size.width, 30)];
self.mSeachBar.delegate = self;
self.mTableView.tableHeaderView = self.mSeachBar;
self.Arr1 = [[NSMutableArray alloc] initWithCapacity:60];
self.Arr2 = [[NSMutableArray alloc] initWithCapacity:60];
for (int i = 0; i < 60; i++) {
NSString *str = [NSString stringWithFormat:@"%d", i];
[self.Arr1 addObject:str];
[self.Arr2 addObject:str];
}
此時行數要改成回傳 Arr2 的數量,繪製時也改從 Arr2 取值:
return [self.Arr2 count]; pCell.textLabel.text = [self.Arr2 objectAtIndex:[indexPath row]];
篩選邏輯本身很直觀:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.Arr2 removeAllObjects];
for (NSString *str in self.Arr1) {
if ([str hasPrefix:self.mSeachBar.text]) {
[self.Arr2 addObject:str];
}
}
[self.mSeachBar resignFirstResponder];
[self.mTableView reloadData];
}
若希望邊打字邊篩選,改為實作 searchBar:textDidChange: 並把 reloadData 搬進去即可。
在導航列右上角放一顆編輯鈕:
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"BegEdit"
style:UIBarButtonItemStylePlain target:self action:@selector(tableViewEdit:)];
self.navigationItem.rightBarButtonItem = item;
- (void)tableViewEdit:(id)sender {
[sender setTitle:[self.mTableView isEditing] ? @"BegEdit" : @"EditEdit"];
[self.mTableView setEditing:![self.mTableView isEditing]];
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return [indexPath row] != 0; // 第一列不可編輯
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return ([indexPath row] % 2)
? UITableViewCellEditingStyleDelete
: UITableViewCellEditingStyleInsert;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.mArr removeObjectAtIndex:[indexPath row]];
[self.mTableView beginUpdates];
[self.mTableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationRight];
[self.mTableView endUpdates];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
[self.mArr insertObject:@"newCell" atIndex:[indexPath row]];
[self.mTableView beginUpdates];
[self.mTableView insertRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationBottom];
[self.mTableView endUpdates];
}
}
順序很重要:永遠先改資料來源,再呼叫表格的刪除/插入方法。顛倒會導致內部索引與資料不同步而崩潰。beginUpdates/endUpdates 成對出現,讓多次變更合併成一次捲動動畫。
- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return [indexPath row] != 2;
}
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath {
NSUInteger from = [sourceIndexPath row];
NSUInteger to = [destinationIndexPath row];
id obj = [self.mArr objectAtIndex:from];
[self.mArr removeObjectAtIndex:from];
[self.mArr insertObject:obj atIndex:to];
}
建立表格時把 style 改成 UITableViewStyleGrouped,再用一個 plist 當資料來源:
NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; self.mDic = [NSDictionary dictionaryWithContentsOfFile:path]; self.mArr = [[self.mDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
plist 的結構是「上層 key 對應下層陣列」,因此各處取值都多一層 section:
// 每組行數
return [[self.mDic objectForKey:[self.mArr objectAtIndex:section]] count];
// 每行標題
pCell.textLabel.text =
[[self.mDic objectForKey:[self.mArr objectAtIndex:section]] objectAtIndex:row];
// 組數
return [self.mArr count];
// 組標題
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
return [self.mArr objectAtIndex:section];
}
// 右側索引欄
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return self.mArr;
}
sectionIndexTitlesForTableView: 回傳的陣列元素必須是字串,且數量要和 section 數量一致,否則點擊索引會跳錯位置。