第八篇、UITableView常用功能(左滑出现多个按钮,多选删除等)

时间:2023-03-09 19:49:26
第八篇、UITableView常用功能(左滑出现多个按钮,多选删除等)

1.左滑动出现多个按钮

/**
* 只要实现了这个方法,左滑出现按钮的功能就有了
(一旦左滑出现了N个按钮,tableView就进入了编辑模式, tableView.editing = YES)
*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{ } /**
* 左滑cell时出现什么按钮
*/
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"关注" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) { // 收回左滑出现的按钮(退出编辑模式)
tableView.editing = NO;
}]; UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
[self.wineArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}]; return @[action1, action0];
}

2.允许多选

// 编辑模式的时候可以多选
self.tableView.allowsMultipleSelectionDuringEditing = YES;
// 进入编辑模式
[self.tableView setEditing:YES animated:YES]; // 获得选中的所有行
self.tableView.indexPathsForSelectedRows;

3.左滑出现删除按钮

/**
* 只要实现了这个方法,左滑出现Delete按钮的功能就有了
* 点击了“左滑出现的Delete按钮”会调用这个方法
*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
// 删除模型
[self.wineArray removeObjectAtIndex:indexPath.row]; // 刷新
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
} /**
* 修改Delete按钮文字为“删除”
*/
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"删除";
}

4.指定行刷新

NSArray *indexPaths = @[
[NSIndexPath indexPathForRow: inSection:],
[NSIndexPath indexPathForRow: inSection:]
];
[self.tableView relaodRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationMiddle];