Could not cast value of type 'UICollectionView

2019-03-09 15:41发布

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 TestProject.CollectionViewCell.

6条回答
贼婆χ
2楼-- · 2019-03-09 15:46

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-03-09 15:54

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
查看更多
劫难
4楼-- · 2019-03-09 16:00

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)
查看更多
成全新的幸福
5楼-- · 2019-03-09 16:09
 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

查看更多
ら.Afraid
6楼-- · 2019-03-09 16:10

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.

Custom Class Section

Document Outline

查看更多
放荡不羁爱自由
7楼-- · 2019-03-09 16:13

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.

查看更多
登录 后发表回答