iOS UITableView 的beginUpdates和endUpdates


在官方文檔中是這樣介紹beginUpdates的

Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: andindexPathsForVisibleRows) to be animated simultaneously. This group of methods must conclude with an invocation ofendUpdates. These method pairs can be nested.

If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid. ---------這句話沒懂

You should not call reloadData within the group; if you call this method within the group, you will need to perform any animations yourself.

 

一般當tableview需要同時執行多個動畫時,才會用到beginUpdates函數,它的本質就是建立了CATransaction這個事務。我們可以通過以下的代碼驗證這個結論

[CATransaction begin];

[CATransaction setCompletionBlock:^{
    // animation has finished
}];

[tableView beginUpdates];
// do some work
[tableView endUpdates];

[CATransaction commit];

這段代碼來自stackoverflow,它的作用就是在tableview的動畫結束后,執行需要的操作。這段代碼好用的原因就是beginUpdates本質上就是添加了一個動畫事務,即CATransaction,當然這個事務可能包含許多操作,比如會重新調整每個cell的高度(但是默認不會重新加載cell)。如果你僅僅更改了UITableView的cell的樣式,那么應該試試能否通過調用beginUpdates 和 reloadRowsAtIndexPaths 來實現效果,而不是調用tableview的reloadData方法去重新加載全部的cell!

一個例子,帶有動畫效果的,重新加載部分cell的代碼。

[tableView beginUpdates];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tmp] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];

下面是一個例子,想實現一個點擊cell,cell的高度就變高的效果,就可以在選中方法中設置標志位,來影響代理方法返回的height值,並且在之后調用

  [tableView beginUpdates];
  [tableView endUpdates];

沒錯,他們之間沒有代碼,算然沒代碼,這2句話會根據代理方法重新調整cell的高度。下面是調用的效果截圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM