1. 程式人生 > >UITableView的 beginUpdates 和 endUpdates<轉>

UITableView的 beginUpdates 和 endUpdates<轉>

成對 option alt count ans 輸出 tab 中間 fin

先看Apple API Reference中對這兩個方法的描述

beginUpdates

技術分享

endUpdates

技術分享

從上述描述中我們大概可以總結出四點

1、beginUpdates 和 endUpdates必須成對使用

2、使用beginUpdates和endUpdates可以在改變一些行(row)的高度時自帶動畫,並且不需要Reload row(不用調用cellForRow,僅僅需要調用heightForRow,這樣效率最高)。

3、在beginUpdates和endUpdates中執行insert,delete,select,reload row時,動畫效果更加同步和順滑,否則動畫卡頓且table的屬性(如row count)可能會失效。

4、在beginUpdates 和 endUpdates中執行 reloadData 方法和直接reloadData一樣,沒有相應的中間動畫。


針對上面幾點舉幾個栗子

1、改變Row的高度

直接調用

[self.tableViewbeginUpdates];

[self.tableViewendUpdates];

接著tableview回調-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath,調整每一行的高度。

技術分享 技術分享

2、同時insert,delete,select reload

[self.tableViewbeginUpdates];

[self.testArrayinsertObject:@(-1)atIndex:0];

[self.tableViewinsertRowsAtIndexPaths:@[[NSIndexPathindexPathForRow:0inSection:0]]withRowAnimation:UITableViewRowAnimationAutomatic];

[self.testArrayremoveObjectAtIndex:3];

[self.tableViewdeleteRowsAtIndexPaths:@[[NSIndexPathindexPathForRow:2inSection:0]]withRowAnimation:UITableViewRowAnimationAutomatic];

[self.tableViewselectRowAtIndexPath:[NSIndexPathindexPathForRow:3inSection:0]animated:YESscrollPosition:UITableViewScrollPositionMiddle];

[self.tableViewreloadRowsAtIndexPaths:@[[NSIndexPathindexPathForRow:4inSection:0]]withRowAnimation:UITableViewRowAnimationAutomatic];

[self.tableViewendUpdates];

技術分享

如何在做完動畫之後執行某個方法呢?

[CATransactionbegin];

[CATransactionsetCompletionBlock:^{

NSLog(@"aferCompletionBlock");

}];

[self.tableViewbeginUpdates];

[self.tableViewendUpdates];

[CATransactioncommit];

如何控制動畫的執行時間呢?

[UIViewanimateWithDuration:2.0fdelay:0.0options:UIViewAnimationOptionCurveEaseInOutanimations:^{

[CATransactionbegin];

[CATransactionsetCompletionBlock:^{

NSLog(@"after2");

}];

[self.tableViewbeginUpdates];

[self.tableViewendUpdates];

[CATransactioncommit];

NSLog(@“after1”);

}completion:^(BOOLfinished) {

NSLog(@"after3");

}];

輸出順序: after1->after2->after3

利用UIView的動畫的執行時間來控制beginUpdates和endUpdates的動畫時間。

UITableView的 beginUpdates 和 endUpdates<轉>