標籤:
#pragma mark -----表視圖的移動操作-----//移動的第一步也是需要將表視圖的編輯狀態開啟//2、指定哪些行可以進行移動- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { //預設都可以移動 return YES;}//3、移動完成之後要做什麼事,怎麼完成移動- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath { //先記錄原有位置下的模型資料 Student *student = _dataArray[sourceIndexPath.row]; [student retain]; //刪除原位置下的模型資料 [_dataArray removeObjectAtIndex:sourceIndexPath.row]; //在新位置將記錄的模型資料添加到資料數組中 [_dataArray insertObject:student atIndex:destinationIndexPath.row]; [student release];}#pragma mark -----刪除、添加資料-----//1、讓將要執行刪除、添加操作的表視圖處於編輯狀態- (void)setEditing:(BOOL)editing animated:(BOOL)animated { //先執行父類中的這個方法。 [super setEditing:editing animated:animated]; //表視圖執行此方法 [self.tableView setEditing:editing animated:animated];}//2、指定表示圖中哪些行可以處於編輯狀態- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {// if (indexPath.row % 2 == 0) {// return YES;// } else {// return NO;// } //預設全部行都可以編輯 return YES;}//3、指定編輯樣式,到底是刪除還是添加 delegate協議裡面- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { //此方法如果不重寫,預設是刪除樣式// return UITableViewCellEditingStyleDelete; return UITableViewCellEditingStyleInsert;}//不管是刪除還是添加,這個方法才是操作的核心方法,當點擊刪除、或者添加按鈕時,需要做什麼事情,怎樣才能完成刪除或者添加操作,全部在這個方法內部指定。- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { [tableView beginUpdates];//表視圖開始更新(可寫可不寫) if (editingStyle == UITableViewCellEditingStyleDelete) { //將該位置下的儲存格刪除 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; //刪除資料數組中與該儲存格繫結資料 [_dataArray removeObjectAtIndex:indexPath.row]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { Student *student = _dataArray[indexPath.row]; //構建一個位置資訊 NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0]; [tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationTop]; [_dataArray insertObject:student atIndex:index.row ]; } [tableView endUpdates];//表視圖結束更新(同樣可寫可不寫,如果寫了[tableView beginUpdates],endUpdates也要寫)
) }
UITableView的添加、刪除、移動操作