Benjamin Gimet Benjamin Gimet - 1 month ago 17
Swift Question

Could not dequeue a view of kind: UICollectionElementKindCell after going back from background

I'm building a Keyboard extension in Swift3.

First time my keyboard is launch, no issue, my collection view is displayed juste fine, everything works.

This bug occurs when my keyboard goes to background and go back again in foreground. For example, I launch iMessage, display my keyboard, tap on the "home button" of my iPhone, launch iMessage again -> crash:


Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier KeyboardViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'


Here is how I set my storyboard for my cell identifier:

Cell identifier

With the right class:

Cell class

And here is how I call it from the
cellForItemAt indexPath
method:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! KeyboardViewCell
return cell


I don't understand why this crash after changing keyboards, like there is no storyboard loaded in that case or something...Did I forgot something?

My storyboard is like this:

enter image description here

enter image description here

Answer

Your KeyboardViewController holds two UICollectionViews. Make sure MyCollectionView is calling its dataSource when dequeueing the KeyboardViewCell in cellForItemAt indexPath:

if collectionView === myCollectionView {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! KeyboardViewCell
    return cell
} else {
    //dequeue soundCollectionViewCell
}