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];spa

          //接着删除单元格 (参数是数组,可能删除多行
          [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];
}
相关文章
相关标签/搜索