ios - 在后台线程上访问 UIView 的属性
问题描述
我试图让我的 CollectionView 在视图出现后滚动它的第一个单元格,然后在按下按钮时再次滚动。问题是 collectionView 没有在任何视图生命周期函数中生成它的所有单元格。
我的解决方案是在后台线程上进行 while 循环,检查是否collectionView.visibleCells.count > 0
,如果是,则返回主线程并滚动到第一个单元格。但是,我收到一个错误,告诉我我不应该访问visibleCells
主线程,并且当我这样做时应用程序会突然出现。
如何在主线程上实现此功能,或检查后台线程中的单元格数量?
private func scrollToFirst() {
DispatchQueue.global(qos: .background).async { [weak self] in
if (self != nil) {
while(self!.collectionView.visibleCells.count != 0) {
DispatchQueue.main.async { [weak self] in
self!.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
}
}
解决方案
有一个委托方法willDisplay会在 collectionViewCell 显示之前被调用。如果您之前没有单元格并且这被调用,那么您知道您将要从零到超过零个单元格。
推荐阅读
- python - Python pandas 将带有数组内容的数据帧附加到 hdf 文件
- python - 使用 Selenium 在下拉按钮中通过正则表达式选择值
- mysql - 如何获取与父表 id 相关的所有孙子
- flutter - 如何跳转到 PageView 中的特定页面?
- amazon-web-services - 使用 CodeDeploy 使用 AppSpec 或脚本设置权限
- css - CSS - 使所有图像都有一个圆形边框
- mysql - MySQL 基于 ID 和 Week 的分区
- ubuntu - 无法连接到 Travis 服务器上的 Mir
- python - 如何在python中的给定正方形中生成统一的新二维数据集
- objective-c - 不兼容的指针类型将“struct NSArray *”传递给“NSArray *”类型的参数