概要:
我们知道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;
}