Search code examples
iosiphoneswiftuicollectionviewuicollectionviewcell

Collection view Cell crashing


I was connecting my Collection view cell to a custom one but it crashes, I already wrote the classname of the custom cell and created the class, but when I am casting the dequeueReusableCell it crashes

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PlatformCollectionViewCell
    if let platformCell = cell as? PlatformCollectionViewCell {
        platformCell.backgroundColor = UIColor.blue
        platformCell.titleLabel.text = "Hola"
        return cell
    }
    cell.backgroundColor = UIColor.green
    return cell
}

The only possible error that I found is when it gives me the error it says something like

Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00). 2017-04-02 13:24:32.711435+0200 Quote[1219:351279] Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00).

I don't know if is okay that it says "NameOfTheProject.Class" in the last line. I think it should say just the class but I don't know how to fix this, in the case this is the error

the class PlatformCollectionViewCell is this

//

import UIKit

class PlatformCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!

}

How I connected the PlatformCell


Solution

  • The error message is telling you exactly what's wrong. The call to collectionView.dequeueReusableCell() is returning a normal UICollectionViewCell, not an instance of your custom cell.

    You need to open our view controller in IB, select the cell prototype with your identifier, and use the "identity inspector" to check the class of that cell. My guess is that you forgot to switch the class to your custom cell class, PlatformCollectionViewCell. If so, simply change UICollectionViewCell``UICollectionViewCell toPlatformCollectionViewCell` in the identity inspector.

    Alternately, you can call register(_:forCellWithReuseIdentifier:) to register an XIB or a class name for your reuse identifier.