標籤:
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];
[email protected]"超級布羅利";
[email protected]"超級賽亞人";
//必須要先插入資料來源
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];}
UITableViewCell儲存格的刪除、插入、移動