Search code examples
iosswiftuitableviewuicollectionviewuicollectionviewcell

multiple collectionView cells inside tableView cells changing design on scroll


I have a tableview with 3 cells that are collectionView 2 has same design cells in tableview goes like

1- category cell (collectionView vertical)

2&3- Product cell (collectionView horizontal)

on scroll the category cell change design to product and same for product it takes category cell design

this is leading to get Break on UIViewReportBrokenSuperviewChain to debug. on collectionView with tag 4

i tried collectionView.collectionViewLayout.invalidateLayout() but things get worse

tableView(cellForrowAt)(
if indexPath.row == 3{
            let cell = self.homeTableView.dequeueReusableCell(withIdentifier: "TableCollectionViewCell") as! TableCollectionViewCell
            cell.collectionView.delegate = self
            cell.collectionView.dataSource = self
            cell.collectionView.tag = 4
            cell.collectionView.isScrollEnabled = false
            return cell
        }
}


collectionView(cellForItemAt){

if collectionView.tag == 4 {
            let nib = UINib(nibName: "ProductCell", bundle: nil)
            collectionView.register(nib, forCellWithReuseIdentifier: "ProductCell")
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as! ProductCell
            cell.setup(product: self.newProducts[indexPath.row])
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
            layout.minimumInteritemSpacing = 10
            layout.minimumLineSpacing = 10
            collectionView.collectionViewLayout = layout
            return cell
        }
}

Solution

  • You shouldn't register your Nib with the collectionView every time you retrieve a cell. You should register all the cell types you are planning to use with a collectionView when it is instantiated/configured or at least check whether that cell is already registered or not.

    Similarly, you shouldn't change the collection view's layout in the code used to retrieve the cell. The layout will in most cases be set once. In some complex cases you may want to change it just prior to dispatching a reloadData() responding to new data being downloaded or some user interations (changing from landscape to portrait, etc).

    Changing the layout during a collection view refresh is likely to produce the unexpected errors you are experiencing.