完美解决UITableView和UICollectionView滚动失效

需求

在新数据源到达后,刷新列表,并直接显示指定位置的item

分析

刷新数据肯定是用 reloadData(),直接显示指定位置,很明显需要用到滚动操作,并且不带滚动动画,直接滚动到指定的位置。

  • 下面以 collectionView 为例,滚动不生效
php 复制代码
collectionView.reloadData()
self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: .right, animated: false)

滚动失效原因

如果直接这样执行,会造成滚动失效,原因 reloadData() 操作可能比较耗时,可能会导致滚动操作在数据刷新完成之前就开始执行,从而导致滚动失效。

解决方案

下面的方法可以完美解决这个问题,就是把滚动操作放入主队列中,当主线程的任务执行完成后,主线程空闲时执行滚动操作。

  • 下面以 collectionView 为例:
php 复制代码
collectionView.reloadData()
DispatchQueue.main.async {
    self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: .right, animated: false)
}
相关推荐
蒙小萌19934 小时前
Performance and metrics
ios
shughui5 小时前
APP、Web、H5、iOS与Android的区别及关系
android·前端·ios
Edward.W7 小时前
iOS 17+真机命令行操作对照表
macos·ios·cocoa
2501_916008891 天前
iOS开发APP上架全流程解析:从开发到App Store的完整指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915909062 天前
Charles 抓不到包怎么办?iOS 调试过程中如何判断请求路径
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 天前
iOS和iPadOS文件管理系统全面解析与使用指南
android·ios·小程序·https·uni-app·iphone·webview
core5122 天前
使用 `ms-swift` 微调 Qwen3-VL-2B 详细指南
lora·微调·swift·qwen·qwen3·vl
core5122 天前
Swift SFT Qwen-VL LoRA 微调指令详解
lora·微调·swift·qwen·vl
2501_915921432 天前
iOS App 开发阶段性能优化,观察 CPU、内存和日志变化
android·ios·性能优化·小程序·uni-app·iphone·webview
游戏开发爱好者82 天前
在 iOS 开发、测试与上架过程中 如何做证书管理
android·ios·小程序·https·uni-app·iphone·webview