項目中經常有對UITableViewCell做各種操作的需求:
- 添加一個新的cell
- 刪除某行cell
- 刷新cell上某行數據(如修改聯系人信息)
- 批量操作cell(訂餐)
Snip20170322_4.png
下面就分別講解一下工作中對Cell的各種操作
刷新數據方法
- 重新刷新屏幕上的所有cell
[self.tableView reloadData];
- 刷新特定行的cell
[self.tableView reloadRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0]
]
withRowAnimation:UITableViewRowAnimationLeft];
- 插入特定行數的cell
[self.tableView insertRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0]
]
withRowAnimation:UITableViewRowAnimationLeft];
- 刪除特定行數的cell
[self.tableView deleteRowsAtIndexPaths:@[
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0]
]
withRowAnimation:UITableViewRowAnimationLeft];
cell批量操作
批量操作cell使用的方法和上面是一樣的澜汤。不同的是批量操作的cell是待選中,然后統一刪除舵匾。
思路:
- 增加model的字段俊抵,設置一個選中標記,可以標識cell的選中狀態(tài)坐梯,防止cell復用出問題
- 在controller中重新創(chuàng)建一個數組徽诲,保存被選中的cell,最后統一刪除數組烛缔。
數據刷新的原則
- 通過修改模型數據馏段,來修改tableView的展示
- 先修改模型數據
- 再調用數據刷新方法
- 不要直接修改cell上面子控件的屬性
小結
修改cell,主要是從數據源中修改践瓷,因為tableview的數據都是從數據源中請求到的院喜。
如果沒有修改數據源,直接修改UI效果晕翠,當tableview滾動的時候tableview重新加載數據源又會覆蓋原來的數據喷舀,導致cell的刷新失敗。