iOSUITableViewCell滑動顯示多個按鈕

在一些應用中我們會看到滑動UITableViewCell會顯示多個按鈕,並且有不同的功能。
這個功能在iOS8之後蘋果提供的一個API可以簡單實現

這裏寫圖片描述

創建UItableView什麼的就不說了
要想讓UITableViewCell有滑動事件就要寫這個方法

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//返回只要是可編輯事件即可
    return UITableViewCellEditingStyleDelete;
}

要想讓UITableViewCell滑動出來的按鈕自定義就要調用

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

在此方法中創建UITableViewCell滑動出來的按鈕,要調用

+ (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(nullable NSString *)title handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler
//點擊進入可以看到簡單的自定義樣式的幾個屬性
 @property (nonatomic, readonly) UITableViewRowActionStyle style;
 @property (nonatomic, copy, nullable) NSString *title;
 @property (nonatomic, copy, nullable) UIColor *backgroundColor; // default background color is dependent on style
 @property (nonatomic, copy, nullable) UIVisualEffect* backgroundEffect;
 //按鈕的事件要寫在block代碼塊中

e.g.

/ 添加一個刪除按鈕
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"刪除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
        // 1. 更新數據
        [_listArray removeObjectAtIndex:indexPath.row];
        // 2. 更新UI
        [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
    }];


    // 添加一個置頂按鈕
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置頂"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
        // 1. 更新數據
        [_listArray exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
        // 2. 更新UI
        NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];

    }];
    //按鈕背景顏色
    topRowAction.backgroundColor = [UIColor blueColor];


    // 添加一個更多按鈕
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"更多"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        [tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationMiddle];

    }];
    moreRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];

    // 將設置好的按鈕放到數組中返回
    return @[deleteRowAction, topRowAction, moreRowAction];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章