列表用 UITableView 展示資料已是基本功,接著幾乎每個 App 都會遇到「要能刪一筆」的需求。想做到「在某一列往左劃,冒出刪除按鈕」,其實不必自訂手勢,實作幾個代理方法即可。
#pragma mark - 初始化 UI
- (void)initUI
{
self.view.backgroundColor = RGB(242, 242, 247);
self.automaticallyAdjustsScrollViewInsets = NO;
sideslipTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, kScreenWidth, kScreenHeight - 60)
style:UITableViewStylePlain];
sideslipTableView.backgroundColor = [UIColor clearColor];
sideslipTableView.delegate = self;
sideslipTableView.dataSource = self;
sideslipTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:sideslipTableView];
}
刪除需要動到資料,所以必須是可變容器:
@interface ViewController () <UITableViewDataSource, UITableViewDelegate> {
UITableView *sideslipTableView;
NSMutableArray *dataArray; // 可變,供刪除使用
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initUI];
dataArray = [NSMutableArray arrayWithArray:@[@"1111", @"2222", @"3333", @"4444",
@"5555", @"6666", @"7777", @"8888", @"9999"]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 46;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *indefier = @"cell";
sideslipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indefier];
if (!cell) {
cell = [[sideslipTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:indefier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.lable.text = dataArray[indexPath.row];
return cell;
}
// 先讓該列可以編輯
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
// 指定編輯樣式為刪除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
// 按下刪除鈕後的實際動作
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[dataArray removeObjectAtIndex:indexPath.row]; // 先改資料
[sideslipTableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationFade]; // 再改畫面
}
}
// 把預設的 Delete 改成中文
- (NSString *)tableView:(UITableView *)tableView
titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除";
}
資料與畫面的順序不能顛倒:必須先從 dataArray 移除元素,再呼叫 deleteRowsAtIndexPaths:。若反過來,reload 時 dataSource 的筆數與 table view 認知不一致,會直接拋出 NSInternalInconsistencyException 而崩潰。
另外,titleForDeleteConfirmationButtonForRowAtIndexPath: 只能改文字,不能改顏色或樣式。若要自訂刪除按鈕外觀(iOS 8 起),可改用 trailingSwipeActionsConfigurationForRowAtIndexPath: 配合 UITableViewRowAction 或 UISwipeActionsConfiguration,彈性大得多。