0
votes

I have a TableView with a CollectionView inside. So each Table cell is the delegate of the CollectionView.

The problem is that the collection View reloads on the main thread and the UITableView Cells are being reused. That causes the collectionView cells to briefly present the labels of previous cells and then fade the changes. How can I hide those labels when the tableView is initially passed through the return cell ?

The problem happens as collection.reload() is applied after the return cell of the UITableView in cell for row.

Here is a sample of the code.

  • UITableViewCell Code
let collectionDatasource = CollectionDataSource()

func configureCell(_ object: CustomClass) {

        //Configure Object for tableView
        self.presentedObject = object
        self.nameLabel.text = object.name

        //Set object and items on collection datasource
        DispatchQueue.main.async {
            let collectionItems = object.collectionItems ?? []
            self.collectionDatasource.object = object
            self.collectionDatasource.items = collectionItems
        }
    }
class CollectionDataSource: NSObject {
    private var collectionView: UICollectionView?
    var items: [CustomItem] = [] {
        didSet {
            DispatchQueue.main.async {
                let changes = [CustomItem].changes(from: oldValue, to: self.items, identifiedBy: ==, comparedBy: <)
                self.collectionView?.apply(changes: changes)
            }
        }
    }
}
1

1 Answers

0
votes

UICollectionView itself does its work asynchronously in contrast to UITableView. So, even if you will call reload collectionView directly in configureCell it will update the collection's cells after the table is set up (still can result in the mentioned issue). But you have added the "reload" call into DispatchQueue.main.async which makes the things worse.

  1. You should skip using DispatchQueue.main.async if possible.

  2. You should replace collectionView with a new one in configureCell. I suggest to add view into the cell of the same size and position as collection view and add collection view in the code. This will guarantee that previous collection view will never appear. 👍