我们在使用一些应用的时候,在滑动一些联系人的某一行的时候,会出现删除、置顶、更多等等的多个按钮,在iOS8之前,我们都需要自己去实现。iOS8之后,只需要一个tableView代理方(tableView:editActionsForRowAtIndexPath:)和一个类(UITableViewRowAction)就可以了。该代理返回的是一个带有UITableViewRowAction的NSArray,自定义设置rowAction之后,之前的delete就会消失。rowAction可以设置style、title、backgroundColor、backgroundEffect,在block中实现点击事件。
以下是创建rowAction的方法和常用属性:
UITableViewRowAction *deleteRowAction = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDefaulttitle:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
[self.arrremoveObjectAtIndex:indexPath.row];
[self.tableViewdeleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationTop];
}];
deleteRowAction.backgroundColor = [UIColorredColor];
deleteRowAction.backgroundEffect = [UIBlurEffecteffectWithStyle:UIBlurEffectStyleDark];
需要注意的是,实现backgroundEffect之后backgroundColor会失效。rowAction的style是一个包含三个类型的枚举
UITableViewRowActionStyleDefault = 0,
UITableViewRowActionStyleDestructive = UITableViewRowActionStyleDefault,
UITableViewRowActionStyleNormal
前两种是显示为红色,normal显示为灰色。
tableView的canEditRowAtIndexPath要设置为YES;
下面是实现的完整代码:
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
//设置删除按钮
UITableViewRowAction *deleteRowAction = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDefaulttitle:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
[self.arrremoveObjectAtIndex:indexPath.row];
[self.tableViewdeleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
}];
//设置收藏按钮
UITableViewRowAction *collectRowAction = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleNormaltitle:@"收藏"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
UIAlertView *alertView = [[UIAlertViewalloc]initWithTitle:@"收藏"message:@"收藏成功"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
[alertView show];
}];
//设置置顶按钮
UITableViewRowAction *topRowAction = [UITableViewRowActionrowActionWithStyle:UITableViewRowActionStyleDefaulttitle:@"置顶"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
[self.arrinsertObject:self.arr[indexPath.row]atIndex:0];
[self.arrremoveObjectAtIndex:indexPath.row +1];
NSIndexSet *set = [NSIndexSetindexSetWithIndex:0];
[tableView reloadSections:setwithRowAnimation:UITableViewRowAnimationTop];
/**
* tableView 刷新时如果确定哪个row 或者section就刷新对应的,不要走reloadData
*/
}];
topRowAction.backgroundColor = [UIColorblueColor];
collectRowAction.backgroundEffect = [UIBlurEffecteffectWithStyle:UIBlurEffectStyleDark];
return @[deleteRowAction,collectRowAction,topRowAction];
}
在tableView刷新时要注意不要改变的局部量的时候不要reloadData,而是刷新对应的section或者row。