Error could not dequeue a view of kind UICollectionElementKindCell

前端 未结 13 1228
耶瑟儿~
耶瑟儿~ 2020-12-16 09:34

Taking first plunge with collection views and am running into this error:

Terminating app due to uncaught exception \'NSInternalInconsistencyException

相关标签:
13条回答
  • 2020-12-16 10:11

    Swift4.0

    Whenever your UITableViewCell is xib at that time you must have to register with UITableView.

    override func viewDidLoad(){
        super.viewDidLoad()
    
        self.yourtableview.register(UINib(nibName: "yourCellXIBname", bundle: Bundle.main), forCellReuseIdentifier: "YourCellReUseIdentifier")
       }
    
    0 讨论(0)
  • 2020-12-16 10:13

    I know this is an old one, but I've experienced the same problem and wanted to share what fixed it for me.

    In my case, I've declared a global identifier

    let identifier = "CollectionViewCell"
    

    and had to use self right before using it:

    collectionView.dequeueReusableCellWithReuseIdentifier(self.identifier, forIndexPath: indexPath) as! CollectionViewCell
    

    Hope this helps someone :)

    0 讨论(0)
  • 2020-12-16 10:16

    I had the same problem.
    When I created a CollectionViewController, the default reuseIdentifier was Cell with capital C, but I made a mistake and made my cell identifier in Storyboard to be cell
    They must be the same.

    0 讨论(0)
  • 2020-12-16 10:18

    From the UICollectionView documentation for the dequeue method:

    Important: You must register a class or nib file using the registerClass:forCellWithReuseIdentifier: or registerNib:forCellWithReuseIdentifier: method before calling this method.

    0 讨论(0)
  • 2020-12-16 10:18

    If you are using storyboard instead of xib, here are few steps.

    1. Making sure you fill the right identifier of your cell.

    1. In the ColletionViewDelegate.

      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
          let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourCellName", for: indexPath)as! YourCellName
          return cell            
      }
      
    2. That's it. You also don't want to add registerClass:forCellWithReuseIdentifier: which will cause element nil error.

    0 讨论(0)
  • 2020-12-16 10:19

    If you create it by code, you must create a custom UICollectionViewCell, Then, init a UICollectionView ,and use loadView to set the view is the UICollectionView that you create. If you create in viewDidload() , it does not work. In addition, you can also drag a UICollectionViewController, it saves a lot of time.

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