Search code examples
swiftuicollectionviewuicollectionviewcellviewcontroller

same collectionview cell using multiple viewcontroller problem


When I try to use the same cell in more than one viewcontroller, I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value error when I try to fill in the labels in the cell.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CategoryCollectionViewCell
        
        cell?.categoryLabel.text = "label"
        
        cell!.contentView.layer.cornerRadius = 7.5
        return cell!
    }

Solution

  • When you design a collection view cell as a prototype in Storyboard:

    enter image description here

    That cell belongs to that collection view and that collection view only. You cannot use it with other collection views or controllers.

    If you want to design a cell that can be used in multiple controllers / collection views, you need to either design it as a XIB or code-only.