UITableView之局部刷新的正确使用姿势

局部刷新

- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);

- (void)insertRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation NS_AVAILABLE_IOS(3_0);

苹果提供了较为丰富的tableView数据源操作方法,想必大家早已是信手拈来.
使用这些方法不仅可以精细的刷新固定的cell,还可以有选择的使用一些动画,相较而言,reloadData则暴力直接了许多.

然而,当我们使用到这些局部刷新的动画时,往往可以发现被刷新的cell会与另一个相同的cell进行交替.


UITableViewRowAnimationLeft

当执行相关的局部操作时,系统会通过tableView的数据源方法来获取进行交替动画的cell.

获取cell

此时如果缓存池中匹配的cell数量不足时,则会根据cell的reuseIdentifier再次创建. 获取完成后,会将被交替的cell隐藏.

值得注意的是即便使用的动画枚举是UITableViewRowAnimationNone,进行交替的cell也依然会被获取或创建.

如果只用来做普通的数据展示,这样重复创建倒也没什么大问题,但是 如果被刷新的cell中有类似播放视频的功能时,就需要注意,如果你使用的播放器是多例,那么在刷新操作时由于多获取了一个播放器cell,那么就会导致出现两个音源的问题.而如果你使用的播放器是单例,那么就需要考虑对于AVPlayerLayer或相关UI的处理.

局部刷新对于含有播放器的Cell的影响

- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection NS_AVAILABLE_IOS(5_0);
- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath NS_AVAILABLE_IOS(5_0);

move相关的方法,由于本身就是通过已存在或将要显示的cell来进行交换动画(纵向),所以不会再特意创建执行交替动画的cell.

关于局部刷新的动画.

UITableViewRowAnimation这个枚举标示了多种动画样式,在一般情况下使用相应的枚举值,都会得到我想要的效果.
然而,当你使用了UITableViewRowAnimationNone这个枚举,并且被刷新的cell有高度和数量的变化时,这时tableView还是会展现一个动画效果.
如果你想禁用这种"隐式动画",可以暂时禁用动画效果达到目的.

    [UIView setAnimationsEnabled:NO]; // 或者[UIView setAnimationsEnabled:NO];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    [UIView setAnimationsEnabled:YES]; // 或者[UIView setAnimationsEnabled:YES];

    // 批量操作
    [CATransaction setDisableActions:YES]; // 或者[UIView setAnimationsEnabled:NO];
    [self.tableView beginUpdates];
    if (deleIndexPaths.count) {
        [self.tableView deleteRowsAtIndexPaths:deleIndexPaths withRowAnimation:UITableViewRowAnimationNone];
    }
    if (insertArray.count) {
        [self.tableView insertRowsAtIndexPaths:insertArray withRowAnimation:UITableViewRowAnimationNone];
    }
    [self.tableView endUpdates];
    [CATransaction setDisableActions:NO]; // 或者[UIView setAnimationsEnabled:YES];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容