collectionView&tableView reloadData时闪烁问题

问题场景

为了实现每次点击collectionView的item时刷新collectionView的数据,并使collectionView自动滚动到所点击item的位置.

问题代码

在reloadData时调用了scrollToItemAtIndexPath:animated方法,并设置animated值为YES

[collectionView reloadData];
[collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

原因分析

reloadData是一个重新加载所有数据源并赋值的方法,赋值时对layer的属性变化会产生隐式动画,又因为animated为YES时collectionView就有一个偏移的动画,而隐式动画也刚好被同时加入了这一时间(duration)之中,就造成了肉眼可见的闪烁效果

解决方案

reloadData时禁用隐式动画

// 禁用隐式动画
[CATransaction setDisableActions:YES];
[collectionView reloadData];
[CATransaction commit];
    
[collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

结论

UITableView和UICollectionView应该大致造成闪烁的原因是相同的,都可以通过此方法解决

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容