Search code examples
iosswiftmultithreadingasynchronouscollectionview

Access a UIView's properties on a background thread


I am trying to have my CollectionView scroll it's first cell after the view appears, and then again whenever a button is pressed. The problem is that the collectionView hasn't generated all it's cells at any of the view lifecycle functions.

My solution is to beging a while loop on a background thread that checks to see if collectionView.visibleCells.count > 0, and when it is, return to the main thread and scroll to the first cell. However, I get an error, telling me that I shouldn't access visibleCells off the main thread, and the app chugs when I do.

How can I achieve this functionality on the main thread, or check the number of cells in the background thread?

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)
                }
            }
        }
    }
}

Solution

  • There is a delegate method willDisplay that gets called right before a collectionViewCell gets displayed. If you previously had no cells and this gets called, then you know you are about to go from zero to more than zero cells.