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

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];
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值