I use a custom CollectionViewCell in my Storyboard. When I start the app I get this message:
Could not cast value of type \'UICollectionViewCell\' to T
The template for a CollectionViewController in Xcode comes with this line of code in viewDidLoad, which changes the specification in your storyboard.
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
Simply delete that line.
In older Swift versions the line is:
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
I received this error when the custom class (on Xcode inspector) still had its class set to the default UICollectionViewCell rather than my custom class for TestProject.CollectionViewCell.
To fix it, simply change the custom class to your implementation.
You will get this error if you register your cell class both in Storyboard and in code. Choose one or the other, never both and the problem goes away.
I wish Apple didn't include this bit of code in their templates:
self.registerClass(SomeUICollectionCellClass.self, forCellWithReuseIdentifier: reuseIdentifier)
Especially since they always recommend you register your cells through Storyboard. Makes things very confusing.
I face this problem , because in the viewDidLoad()
I registered my cell with UICollectionViewCell class . In my cellForItemAtIndexPath
used CustomSubcalssCollectionViewCell for dequeueReusableCell.
make sure registerClass and dequeueReusableCell are the same class solve the problem
self.registerClass(SomeUICollectionCellClass.self, forCellWithReuseIdentifier: reuseIdentifier)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SomeUICollectionCellClass
I hit this error when instantiating a ViewController
from a Storyboard in my unit test.
storyboard.instantiateViewControllerWithIdentifier("someVC") as! MyViewController
The problem was that I had assigned a specific module in the Identity inspector to that VC in the Storyboard. I removed it so it defaults to the current module which is the application module while running and the Test module while testing.
self.collectionView!
.register(MyCollectionViewCell.self,
forCellWithReuseIdentifier: reuseIdentifier
)
You don't have to delete this line. You will register your own cell class inherited by UICollectionViewCell.self
if you want to register class using code