您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableView 左滑手勢自訂:不只刪除,還能加入置頂等操作

編輯:iOS 開發綜合

前言

UITableView 內建的左滑刪除是 iOS 裡辨識度很高的互動之一,操作直覺、動畫順手。但實務上,使用者往左滑之後想做的事往往不只「刪除」——可能還想要「取消收藏」「置頂」「標為已讀」等等。這時候就不能只依賴系統預設行為,而該自己定義一組滑動動作。

實作方式

做法是實作 tableView:editActionsForRowAtIndexPath:,回傳一個由 UITableViewRowAction 組成的陣列,每個物件代表一個按鈕。

 -(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;
}

幾個實務細節

按鈕順序:陣列中的排列順序與畫面上由右至左的顯示順序相反,也就是最後一列的按鈕會最靠近 cell 右緣。若希望「刪除」在最外側,就要把它放在陣列最後。

顏色可自訂:每個 action 都有 backgroundColor 屬性,可以個別指定,不必受限於系統的紅色刪除樣式。

要讓左滑生效:記得在需要的方法中回傳 UITableViewRowActionStyleDefault 之外的設定,並確認 canEditRowAtIndexPath: 回傳 YES,否則手勢不會啟動。

整體而言,透過 UITableViewRowAction 建立物件、把點擊邏輯寫在 block 裡、再把物件放進陣列回傳,就能自由擴充左滑選單的項目與外觀,彈性相當高。

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