UITableVIew 編輯

UITableView的編輯: 刪除,添加
應用場景:通訊錄 中刪除聯繫人,添加聯繫人
編輯的步驟:
1.開啓UITableView的編輯狀態
這步需要注意的是一般會在一個按鈕裏面寫, 有開有肯定有關編輯狀態,再點一下這個按鈕,關閉編輯狀態. 我們利用了tableView 的 editing屬性(BOOL型)
[self.tableView setEditing:!self.tableView.editing animated:YES];
!self.tableView.editing 對tableView編輯狀態取反
並且可以在開啓編輯時按鈕一個title, 關閉時另一個title

2.允許編輯 返回值是BOOL型 默認是YES
方法: - (BOOL)tableView:(UITableView )tableView canEditRowAtIndexPath:(NSIndexPath )indexPath
這裏可以利用indexPath控制哪個分區的哪一行不能編輯

3.指定編輯樣式. 主要是刪除,添加
方法: - (UITableViewCellEditingStyle)tableView:(UITableView )tableView editingStyleForRowAtIndexPath:(NSIndexPath )indexPath
與第二步一樣,利用indexPath控制哪個分區的哪一行的編輯樣式
刪除:UITableViewCellEditingStyleDelete
添加: UITableViewCellEditingStyleInsert

  1. 提交編輯
    方法: (void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath
    根據編輯樣式和索引去完成編輯
    通訊錄爲例:
    刪除時: 1.刪除數據
    2.判斷分區裏面已經沒數據 沒有刪除行
    3.刷新界面 兩種: a.整體刷新 [tableView reloadData]; b.刪除自帶的刷新方法 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
    添加同刪除.

移動步驟
1.開啓編輯狀態
2.允許哪一個分區的哪一行可以移動
3.提交移動 - (void)tableView:(UITableView )tableView moveRowAtIndexPath:(NSIndexPath )sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
1.操作數據源數組 a.把來源索引下數組對應的元素保存一下
b.用來源的索引 刪除數組中對應元素
c.插入到移動目的地索引處
d.刷新 [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
4.限制跨區移動 一般情況下我們是隻讓其同區之間進行移動
- (NSIndexPath )tableView:(UITableView )tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath )sourceIndexPath toProposedIndexPath:(NSIndexPath )proposedDestinationIndexPath
可以判斷來源索引與建議目的地索引的section是否相同,相同說明是同區,返回目的地索引,反之返回來源索引

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章