Search code examples
iosswiftuicollectionviewuicollectionviewcell

Value of type 'UICollectionViewCell?' has no member 'contentImage'


I have two custom UICollectionViewCells(AddImageCollectionViewCell, ItemCollectionViewCell) which I am loading depending on indexpath. Here is my code for the cellForItemAtIndexpath-

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

        var cell :UICollectionViewCell!

        if indexPath.row == 0{
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
        }
        else{
             cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
            cell.contentImage = self.droppedItemList[indexPath.row] //error here
        }
        return cell
    }

I am getting the error as "Value of type 'UICollectionViewCell?' has no member 'contentImage'". Why is my cell in the else clause is not cast to "ItemCollectionViewCell" type.

I know, I must be doing something very foolish. I would be really grateful if someone can point me to the right direction.


Solution

  • You are declaring cell as basic type UICollectionViewCell, that's the reason. Return the cells separately

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addImageCell", for: indexPath) as! AddImageCollectionViewCell
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCollectionViewCell
            cell.contentImage = self.droppedItemList[indexPath.row]
            return cell
        }
    }