UITableViewCell单元格的删除、插入、移动

UITableViewDelegate的方法
 
    设置 编辑模式 中得cell的编辑样式 (删除或插入)
     - (UITableViewCellEditingStyle) tableView:(UITableView *)tableView  editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
 
UITableViewDataSource的方法
     
     设置该单元格能否被编辑
     - (BOOL)tableView:(UITableView *)tableView  canEditRowAtIndexPath:(NSIndexPath *)indexPath;
     设置该单元格能否被移动
     - (BOOL) tableView:(UITableView *)tableView  canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
 
      对单元格进行编辑 时会调用此方法
 
删除单元格:1)先 删除数据源 2)接着 删除单元格 3)刷新单元格
插入单元格:1)先 插入数据源 2)接着 插入单元格 3)刷新单元格
 
     - (void) tableView:(UITableView *)tableView  commitEditingStyle:(UITableViewCellEditingStyle)editingStyle  forRowAtIndexPath:(NSIndexPath *)indexPath
{
      //判断编辑样式(删除或插入)
     if (editingStyle== UITableViewCellEditingStyleDelete)  
     {  
      //必须要先删除数据

          NSMutableArray *arr=[self.dataSourceArray objectAtIndex:indexPath.section];

          [arr removeObjectAtIndex:indexPath.row];

          //接着删除单元格 (参数是数组,可能删除多行
          [tableView deleteRowsAtIndexPaths:[ NSArray arrayWithObject :indexPath] withRowAnimation:UITableViewRowAnimationFade];
          //删除完后要刷新tableView
          [tableView reloadData];
     }
     else if (editingStyle==UITableViewCellEditingStyleInsert)   //插入模式
     {
          //下面根据实际情况
          CSFriends *friend=[[CSFriends alloc]init];
          friend.imageName=[NSString stringWithFormat:@"%d.jpg",2];
          friend.name=@"超级布罗利";
          friend.skill=@"超级赛亚人";
          //必须要先插入数据源
          NSMutableArray *arr=[ self. dataSourceArray  objectAtIndex :indexPath. section ];
          [arr insertObject:friend atIndex:indexPath.row];
          //接着插入单元格 (参数是数组,可能插入多行
          [tableView insertRowsAtIndexPaths:[ NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
          //插入后要刷新tableView
          [tableView reloadData];
    }
}
 
      对单元格进行移动时会调用此方法
 
移动单元格:1)先将要移动的数据从 数据源的原位置中 删除 2)接着再讲数据 插入数据源的新位置 3)刷新单元格
 
     -(void) tableView:(UITableView *)tableView  moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath  toIndexPath:(NSIndexPath *)destinationIndexPath
{
      //先找到要移动的数据(sourceIndexPath是移动前的位置)
      NSMutableArray *array= self.  dataSourceArray [ sourceIndexPath . section ];
      CSFriends  *friend= array[ sourceIndexPath .row];
      // 将该数据从数据源删除
     [array  removeObject:friend];
      //再找到新位置的数据源 (destinationIndexPath是移动后的位置)
      NSMutableArray *array= self.  dataSourceArray [ destinationIndexPath . section ];
      //将数据先添加入数据源的新位置
     [array insertObject:friend  atIndex: destinationIndexPath. row];
      //最后刷新单元格
     [tableView reloadData];
}
 
 
 
 
 

转载于:https://www.cnblogs.com/hcsaaron/p/4379344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值