IOS Cell 的刪除 增加 移動操作

//當前行是否可以編輯

-(BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath {

if(indexPath.row==0)returnNO;

returnYES;

}

//當前行是如何編輯(刪除增加)

-(UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath {

//最后一行插入

if(indexPath.row==self.mArray.count-1)

returnUITableViewCellEditingStyleInsert;

//其他行刪除

returnUITableViewCellEditingStyleDelete;

}

//編輯后(刪除或增加)如何處理

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {

if(editingStyle ==UITableViewCellEditingStyleDelete) {

NSLog(@"刪除元素");

//先把數組中的元素刪除

[self.mArrayremoveObjectAtIndex:indexPath.row];

[tableViewreloadData];

//[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

}elseif(editingStyle ==UITableViewCellEditingStyleInsert) {

NSLog(@"插入元素");

//先向數組中插入元素

[self.mArrayaddObject:@"趙六"];

//[tableView reloadData];

NSIndexPath*myIndexPath = [NSIndexPathindexPathForRow:self.mArray.count-1inSection:0];

[tableViewinsertRowsAtIndexPaths:@[myIndexPath]withRowAnimation:UITableViewRowAnimationLeft];

NSLog(@"--- %@",self.mArray);

}

}

//當前行是否可以移動

-(BOOL)tableView:(UITableView*)tableView canMoveRowAtIndexPath:(nonnullNSIndexPath*)indexPath {

returnYES;

}

//移動完成后如何操作

-(void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {

//移動完成后數組里的元素也應該交換位置

NSString*name =self.mArray[sourceIndexPath.row];

//從數組中刪除

[self.mArrayremoveObjectAtIndex:sourceIndexPath.row];

//把元素插入到目標的位置

[self.mArrayinsertObject:nameatIndex:destinationIndexPath.row];

[tableViewreloadData];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容