iOS_8_API:UITableViewRowAction

概要:
我们知道UITableView的cell水平方向向左滑动时,默认会出现一个删除按键, 如果想添加自定的按钮需要重新封装才能实现.
iOS8中提供的新的API-UITableViewRowAction, 可以很方便的添加自定义的按钮

文章中尽量不使用或少使用封装, 目的是让大家清楚为了实现功能所需要的官方核心API是哪些(如果使用封装, 会在封装外面加以注释)

  • 此文章由 @Scott 编写. 经 @春雨,@黑子 审核. 若转载此文章,请注明出处和作者

<功能描述>

核心API

Class : UITableViewRowAction, UITableView
Delegate : UITableViewDelegate
涉及的API:

/** UITableViewDelegate 相关协议方法 */
- (NSArray<UITableViewRowAction *> * _Nullable)tableView:(UITableView * _Nonnull)tableView editActionsForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath

/** UITableViewRowAction 类API(一共有4个属性和一个类方法) */

@property(nonatomic, readonly) UITableViewRowActionStyle style
@property(nonatomic, copy) NSString *title
@property(nonatomic, copy) UIColor *backgroundColor
@property(nonatomic, copy) UIVisualEffect *backgroundEffect

+ (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(NSString *)title handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler

这里写图片描述

Code:

在tabelView 的Cell上添加一个自定义的按钮, 需要实现UITableViewDelegate协议中的tableView:editActionsForRowAtIndexPath:方法

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{

    /** 
     * 创建第一个action
     * 参数1: action的风格样式(枚举值)
     * 参数2: 按钮的标题
     * 参数3: block块, 当点击按钮时执行的代码段
     */
    UITableViewRowAction *rowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        /** 当点击按键之后执行的代码段 */


    }];

    /** 创建第二个action */
    UITableViewRowAction *rowAction2 = [UITableViewRowAction rowActionWithStyle:0 title:@"收藏" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        /** 当点击按键之后执行的代码段 */



    }];

    /** 设置按键的背景颜色 */
    rowAction2.backgroundColor = [UIColor greenColor];


    /**  创建第三个action */
    UITableViewRowAction *rowAction3 = [UITableViewRowAction rowActionWithStyle:0 title:@"分享" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

        /** 当点击按键之后执行的代码段 */

    }];

    rowAction3.backgroundColor = [UIColor orangeColor];


    /** 将action对象加入数组中 */
    NSArray *arr = [NSArray arrayWithObjects:rowAction1, rowAction2, rowAction3, nil];

    /** 返回数组 */
    return arr;


}

Demo的GitHub链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值