首页 > 解决方案 > 在后台线程上访问 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)
                }
            }
        }
    }
}

标签: iosswiftmultithreadingasynchronouscollectionview

解决方案


有一个委托方法willDisplay会在 collectionViewCell 显示之前被调用。如果您之前没有单元格并且这被调用,那么您知道您将要从零到超过零个单元格。


推荐阅读