Could not cast value of type 'UICollectionViewCell'

后端 未结 6 1105
野性不改
野性不改 2021-02-01 12:21

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

相关标签:
6条回答
  • 2021-02-01 12:57

    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)
    
    0 讨论(0)
  • 2021-02-01 12:58

    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.

    0 讨论(0)
  • 2021-02-01 13:07

    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.

    0 讨论(0)
  • 2021-02-01 13:09

    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
    
    0 讨论(0)
  • 2021-02-01 13:12

    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.

    0 讨论(0)
  • 2021-02-01 13:13
     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

    0 讨论(0)
提交回复
热议问题