在 UITableView 的應用中,刪除列與拖曳排序是非常常見的互動需求。要實現這兩項功能,核心都在於正確實作對應的代理方法,並同步維護底層的資料來源陣列。以下直接透過代理方法來說明。
#pragma mark -代理方法
#pragma mark 設置cell表格高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60;
}
#pragma mark 當cell實行編輯功能時調用
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if(editingStyle!=UITableViewCellEditingStyleDelete) return;
//1.刪除數據源數據
[_persons removeObject:_persons[indexPath.row]];
//2.重新加載數據
[self.tableView reloadData];
}
#pragma mark 當cell實行排序功能時調用
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
//1 拿出要移動的數據,並刪除
Person *p=_persons[sourceIndexPath.row];
[_persons removeObject:p];
//2 把要移動的數據添加到目的位置
[_persons insertObject:p atIndex:destinationIndexPath.row];
}
#pragma mark 監聽刪除按鈕
- (IBAction)remove:(UIBarButtonItem *)sender {
// self.tableView.editing=YES;//進入編輯模式
BOOL result=!self.tableView.isEditing;
[self.tableView setEditing:result animated:YES];
}
重點在於:刪除時要在 commitEditingStyle 中先從資料來源移除對應物件再刷新;排序時則是在 moveRowAtIndexPath 中先取出要移動的物件、從原位置移除,再插入到目標位置。只要資料來源與畫面保持同步,刪除與排序就能流暢運作。