您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

UITableView 的刪除列與排序功能:代理方法實作全解析

編輯:iOS 技巧大全
[摘要]本文聚焦 UITableView 的刪除列與列排序功能,透過關鍵代理方法的示範,說明如何處理資料源的增刪與重新排序,是學習 iOS 列表操作的實用範例。

在 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 中先取出要移動的物件、從原位置移除,再插入到目標位置。只要資料來源與畫面保持同步,刪除與排序就能流暢運作。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved