在官方文档中是这样介绍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的高度。下面是调用的效果截图: