您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 自訂 UITableView 左滑操作:一次放進多個按鈕

編輯:iOS 7 技巧

左滑刪除是 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;
}

觀念拆解

整個機制只有三件事:

  1. 用 UITableViewRowAction 建立 action 物件,title 就是按鈕文字,handler 這個 block 是點擊後要執行的程式。
  2. 每個 action 的 backgroundColor 可以個別指定,顏色完全由你決定。
  3. 把這些 action 放進陣列回傳,左滑就會一次展開全部按鈕。

要特別注意的是陣列順序決定顯示順序,而且最左邊那顆(陣列第一個)通常會被視為最靠近手指、最容易誤觸的位置,破壞性操作建議不要放在那裡。

另外記得實作 canEditRowAtIndexPath 回傳 YES,否則滑不出任何東西——這是新手最常卡住的一點。

相較於舊的 titleForDeleteConfirmationButton(只能改刪除按鈕文字),RowAction 這套 API 從 iOS 8 起提供,靈活度高得多,新專案沒理由再用舊寫法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved