ios 编辑UITableView (添加数据 删除数据)

xiaoxiao2021-02-28  29

1 实现uitablview 代理方法 2 commitEditingStyle 实现后 可初步右滑删除 及添加删除代码

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (editingStyle == UITableViewCellEditingStyleDelete) { //删除数据源 [self.contacts removeObjectAtIndex:indexPath.row]; //删除cell [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop]; }else if(editingStyle == UITableViewCellEditingStyleInsert){ LATCellModel * model = [[LATCellModel alloc] init]; model.name = @"lidjsis" ; model.phone = @"82738104234719"; //添加数据源 [self.contacts insertObject:model atIndex:indexPath.row+1]; //创建indexpath NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; //添加cell [tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationTop]; } }

3 - (UITableViewCellEditingStyle)tableView:(UITableView )tableView editingStyleForRowAtIndexPath:(NSIndexPath)indexPath //通过这个方法可以区分每个项目时候删除或添加

- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ if (indexPath.row%2==0) { return UITableViewCellEditingStyleInsert ; }else{ return UITableViewCellEditingStyleDelete ; } }

4编辑删除按钮的文字

-(NSString *) tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ return @"删除"; }

5 UITableview设置是否可编辑

[self.tableView setEditing:!self.tableView.editing animated:YES];
转载请注明原文地址: https://www.6miu.com/read-2150098.html

最新回复(0)