左滑刪除是 UITableView 最經典的互動之一,但實務需求往往不只「刪除」——可能還要「置頂」、「標為已讀」、「取消收藏」。系統只給一個預設按鈕根本不夠用,這時候就該改用 editActionsForRowAtIndexPath 自己組。
-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
title:@"取消收藏" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"收藏點擊事件");
}];
UITableViewRowAction *rowAction2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
title:@"頂置" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"頂置按鈕點擊事件");
}];
rowAction.backgroundColor = RGB(215, 59, 16);
NSArray *arr = @[rowAction, rowAction2];
return arr;
}
整個機制只有三件事:
UITableViewRowAction 建立 action 物件,title 就是按鈕文字,handler 這個 block 是點擊後要執行的程式。要特別注意的是陣列順序決定顯示順序,而且最左邊那顆(陣列第一個)通常會被視為最靠近手指、最容易誤觸的位置,破壞性操作建議不要放在那裡。
另外記得實作 canEditRowAtIndexPath 回傳 YES,否則滑不出任何東西——這是新手最常卡住的一點。
相較於舊的 titleForDeleteConfirmationButton(只能改刪除按鈕文字),RowAction 這套 API 從 iOS 8 起提供,靈活度高得多,新專案沒理由再用舊寫法。