I have a custom cell that i create from xib.
It looks like this:
And i have 2 other cells created only in class that subclass it.
And need to add different views to the containerView
So in my UIViewController
i register all cells.
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(cell1.self, forCellWithReuseIdentifier: "cell1")
collectionView.register(cell2.self, forCellWithReuseIdentifier: "cell2")
collectionView.register(UINib(nibName: "ParentCell", bundle: nil), forCellWithReuseIdentifier: "parentCell")
}
}
and dequeueing the cells.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! cell1
cell.containerView.backgroundColor = UIColor.yellow
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as! cell2
cell.containerView.backgroundColor = UIColor.red
return cell
}
but the app crashes with
fatal error: unexpectedly found nil while unwrapping an Optional value
when i try to use containerView
Any suggestions how to implement this?
Thanks
EDIT:
My problem is that the views from the parent cell are not getting instantiated. I understand what
fatal error: unexpectedly found nil while unwrapping an Optional value
means. i dont understand why are the view not getting instantiated.
The crash is on
cell.containerView.backgroundColor