当咱们在使用tableview时,每每须要在cell左滑时显示一个或是多个按钮,但系统默认的只可显示一个,如常见的删除按钮,那么当咱们的需求要求要有多个按钮时又该怎么办呢,咱们往下看。测试
如须要显示多个按钮,参照以下代码(注意:当咱们使用自定义按钮后,如上的系统默认方法将失去做用)
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
returntrue;
}
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnullNSIndexPath *)indexPath{
UITableViewRowAction *action1 = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleNormaltitle:@"加入黑名单"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//在block中实现相对应的事件
}];
UITableViewRowAction *action2 = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDestructivetitle:@"删除"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[callRecordsArrremoveObjectAtIndex:indexPath.row];
//数据源删除对应元素要在tableview删除对应的cell以前
[tableView deleteRowsAtIndexPaths:[NSMutableArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[NSKeyedArchiverarchiveRootObject:callRecordsArrtoFile:CALLRECORDSCACHEPATH];
}];
action2.backgroundColor = [UIColorpurpleColor];
注意:一、当rowActionWithStyle的值为UITableViewRowActionStyleDestructive时,系统默认背景色为红色;当值为UITableViewRowActionStyleNormal时,背景色默认为淡灰色,可经过UITableViewRowAction的对象的.backgroundColor设置;
二、当左滑按钮执行的操做涉及数据源和页面的更新时,要先更新数据源,在更新视图,不然会出现无响应的状况
UITableViewRowAction *toTop = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDestructivetitle:@"置顶"handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//更新数据
[callRecordsArrexchangeObjectAtIndex:indexPath.rowwithObjectAtIndex:0];
//更新页面
NSIndexPath *firstIndexPath = [NSIndexPathindexPathForRow:0inSection:indexPath.section];
[tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
}];
//此处UITableViewRowAction对象放入的顺序决定了对应按钮在cell中的顺序
return@[toTop,action2,action1];
}
显示图形以下
在这要补充一点的就是,我在查相关资料时,上面自定义按钮时,都加上了“orm
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath对象
{blog
}”这个方法,而我在实验测试时发现没有这个方法也一样能实现预期功能,而且也没有发现什么bug,所以本次总结的方法只供参考,如果哪位大神知道这一点的,请不吝赐教!事件