UITableView的 beginUpdates 和 endUpdates

先看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的動畫時間。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容