清單類 App 幾乎一定會遇到「往左滑出現刪除鈕」的需求。UITableView 本身就把這套互動做好了,我們只要提供資料源並實作兩個委派方法。以下拆解成幾個步驟。
因為要刪資料,容器必須是可變的:
#import <UIKit/UIKit.h>
@interface UITableCellSwapDeleteViewController : UIViewController <UITableViewDelegate>
{
IBOutlet UITableView *testTableView;
NSMutableArray *dataArray;
}
@property (nonatomic, retain) UITableView *testTableView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@end
- (void)viewDidLoad {
[super viewDidLoad];
dataArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
return cell;
}
三個方法一組,資料就顯示出來了。這裡刻意示範手動建立 cell,實務上若在 storyboard 或 xib 中註冊過 reuse identifier,dequeueReusableCellWithIdentifier: 永不會回傳 nil,那個 if 分支可以省掉。
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[dataArray removeObjectAtIndex:indexPath.row]; // 先改資料
[testTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// 需要插入功能時,在此建立物件、加入陣列並插入新列
}
}
在任一列往右滑一下,刪除鈕就出現了,點下去該列會以淡出動畫消失。
順序很重要:一定要先更新資料源,再呼叫 deleteRowsAtIndexPaths:。若顛倒,UITableView 在動畫過程中回查 row count 會發現資料對不上,直接丟出 NSInternalInconsistencyException 崩潰。這是新手最常踩的坑。
系統預設的按鈕文字是 Delete。想換成「下載」這類符合語境的詞,再實作一個委派方法就好:
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
return @"下載";
}
再滑一次,按鈕文字就變了。如果連「刪除」以外的動作(例如置頂、標記)也想放進滑動選單,iOS 8 之後可以改用 editActionsForRowAtIndexPath: 搭配 UITableViewRowAction,能自訂多個按鈕與各自顏色,比單一刪除鈕靈活得多。