UITableView的編輯

創建UITableView的幾個步驟

  • 第一步:遵循協議
  • 第二步:創建UITableView
  • 第三步:設置代理和數據源
  • 第四步:將UITableView添加到視圖上
  • 第五步:實現協議中必須實現的方法

TableView的編輯

<1>刪除
第一步:打開視圖的交互
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{      
     [self.tableView setEditing:editing animated:animated];
}
第二步:設置是否可以編輯
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{    return YES;
}
第三步:設置編輯狀態
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{     
    return UITableViewCellEditingStyleNone;    
    //return   UITableViewCellEditingStyleDelete;  刪除  
    //return   UITableViewCellEditingStyleInsert;  添加   
}
第四步:提交編輯狀態,處理對應數據源
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
  //判定編輯狀態
  if (editingStyle == UITableViewCellEditingStyleDelete) {           
        [self.array removeObjectAtIndex:indexPath.row];       
       //第一種1:加載數據(具體的某一行) 
        //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationRight)];                        
       //第二種2:直接使視圖重新加載數據
       [tableView reloadData];
    }   
  if(editingStyle == UITableViewCellEditingStyleInsert){
     [self.array insertObject:@"AAAAAAA" atIndex:indexPath.row+1];
     //第一種1:加載數據(具體的某一行)
     NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section];  
    [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationRight];
    //第二種2:直接使視圖重新加載數據
    //[tableView reloadData];
   }
 }
<2>移動
第一步: 使TableView處于編輯狀態
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
//調用父類編輯方法
[super setEditing:editing animated:animated];
//使當前tableView處于編輯狀態
[self.tableView setEditing:editing animated:animated];  
//編輯按鈕文字
self.editButtonItem.title = editing ? @"完成" : @"編輯";
}
//第二步 : 完成移動
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
  //根據原路徑找到對應的分組
  NSMutableArray *array = self.dataDic[self.dataArray[sourceIndexPath.section]];
  //再找到對應的row(保存到model類中)
  Model *model = array[sourceIndexPath.row];
  //先刪除
  [array removeObjectAtIndex:sourceIndexPath.row];
  //添加到目的路徑
  [array insertObject:model atIndex:destinationIndexPath.row];
}
//第三步 : 檢測跨區越界
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath{
>  
   //若計劃目的路徑分區和原路徑分區相同, 直接返回計劃目的路徑
  //若是同一個分區
  if (sourceIndexPath.section == proposedDestinationIndexPath.section) {
    //則到目的路徑
    return proposedDestinationIndexPath;
  >    
   }else{
      //否則 返回原組
      return sourceIndexPath;
   }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容