Bhavesh Odedara
Bhavesh Odedara

Reputation: 79

My UICollectionViewCell item is nil?

My CollectionViewCell imageView is nil

My Cell File is here

class MyTicketsCollectionViewCell: UICollectionViewCell {

     @IBOutlet weak var imgTicket: UIImageView!
}

My Controller File Code is here

class MyTicketsCollectionViewController: UICollectionViewController {

     var photos: [String] = ["ticket1","ticket2","ticket3","ticket4"]

     override func viewDidLoad() {
     super.viewDidLoad()

         self.collectionView?.register(MyTicketsCollectionViewCell.self, forCellWithReuseIdentifier: "MyTicketsCollectionViewCell")

     }

     override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

         return photos.count
     }

     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell

         cell.imgTicket.image = UIImage(named: photos[indexPath.row])

        return cell
    }

}

Error is "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

When I debug it then

 cell.imgTicket is nil

How solve this issue?

Upvotes: 1

Views: 1192

Answers (3)

Avineet Gupta
Avineet Gupta

Reputation: 596

There is 2 possible solutions here...

1. Might be ActiveTicketsCollectionViewCell have not the property imgTicket or you mention a wrong cell class here as u have mentioned a different cell class name MyTicketsCollectionViewCell so try to write this code.

  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell

  cell.imgTicket.image = UIImage(named: photos[indexPath.row])

  return cell

2. Might be you have missed to connect your property (@IBOutlet weak var imgTicket: UIImageView!) with the Outlet (xib or storyboard).

Upvotes: 0

DionizB
DionizB

Reputation: 1507

Try changing your code to

   override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell

     cell.imgTicket.image = UIImage(named: photos[indexPath.row])

    return cell
}

Upvotes: 1

Qi Hao
Qi Hao

Reputation: 36

You are dequeuing ActiveTicketsCollectionViewCell but the cell is registered under MyTicketsCollectionViewCell.

Upvotes: 0

Related Questions