2

I have a custom cell that i create from xib.

It looks like this:

collectionViewCell

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
Confused
  • 6,048
  • 6
  • 34
  • 75
ilan
  • 4,402
  • 6
  • 40
  • 76
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Bista Jan 24 '17 at 09:48
  • @Mr.Bista please read my question again, its not the same. – ilan Jan 24 '17 at 09:49
  • I know, but error is self explanatory, also can you point out on exactly which line the error occurs? – Bista Jan 24 '17 at 09:54
  • See my edit... this doesn't help... thanks anyway – ilan Jan 24 '17 at 09:54
  • "i dont understand why are the view not getting instantiated." , you might have put wrong cell identifier name. – Bista Jan 24 '17 at 09:54
  • no, the right cell is getting instantiated, the parent views from the xib are not. – ilan Jan 24 '17 at 09:55

0 Answers0