UITableView對(duì)于iOS開發(fā)者來(lái)說(shuō)一定不會(huì)陌生,很有可能你的APP很多界面都用到它。關(guān)于UITableView的文章,想必已經(jīng)不計(jì)其數(shù),沒(méi)事可以多看看。特別是UITableView優(yōu)化的文章,非常值得仔細(xì)琢磨一番。
今天我們來(lái)看看如何刷新UITableView的,一般情況下,刷新UITableView,我們會(huì)直接調(diào)用reloadData方法。
1.刷新UITableView
[self.tableView reloadData];
reloadData是刷新整個(gè)UITableView,有時(shí)候,我們可能需要局部刷新。比如:只刷新一個(gè)cell、只刷新一個(gè)section等等。這個(gè)時(shí)候在調(diào)用reloadData方法,雖然用戶看不出來(lái),但是有些浪費(fèi)資源。
2.刷新局部cell
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
這樣就可以很方便的刷新第一個(gè)section的第一個(gè)cell。雖然看起來(lái)代碼多了,但是確實(shí)比較節(jié)省資源。盡量少的刷新,也是UITableView的一種優(yōu)化。
3.局部刷新section
NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
[self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
上面這段代碼是刷新第0個(gè)section。
4.左滑動(dòng)刪除cell或者section(以model為例)
HistoryModel*m =_dataArray[indexPath.section];
HistoryInfoModel*tempModel = m.data[indexPath.row];
//刪除某一行
//1.更新數(shù)據(jù)
[m.dataremoveObjectAtIndex:indexPath.row];
//[myTableView reloadData];//浪費(fèi)資源
//2.局部更新UI
if(m.data.count>0) {
[myTableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObjects:indexPath,nil]withRowAnimation:UITableViewRowAnimationFade];
}else{
//這里是刪除整個(gè)section
[_dataArrayremoveObject:m];
[myTableViewdeleteSections:[NSIndexSetindexSetWithIndex:indexPath.section]withRowAnimation:UITableViewRowAnimationFade];
}
刷新動(dòng)畫
刷新UITableView還有幾個(gè)動(dòng)畫:
typedef NS_ENUM(NSInteger, UITableViewRowAnimation) {
UITableViewRowAnimationFade, ? //淡入淡出
UITableViewRowAnimationRight, ?//從右滑入 ? ? ? ? // slide in from right (or out to right)
UITableViewRowAnimationLeft, ? //從左滑入
UITableViewRowAnimationTop, ? ? //從上滑入
UITableViewRowAnimationBottom, ?//從下滑入
UITableViewRowAnimationNone, ? ? ? ? ? ?// available in iOS 3.0
UITableViewRowAnimationMiddle, ? ? ? ? ?// available in iOS 3.2. ?attempts to keep cell centered in the space it will/did occupy
UITableViewRowAnimationAutomatic = 100 ?// available in iOS 5.0. ?chooses an appropriate animation style for you
};