Marie Dm
Marie Dm

Reputation: 2727

UIViewController xib file containing a collectionview with a custom cell

I have a xib file containing an UIViewController called FullScreenGalleryVC. It contains a UICollectionView that contains a custom UICollectionViewCell, which identifier is fullscreen_cell.

When I want to create a new FullScreenGalleryVC, I call FullscreenGalleryVC.display(from: self).

Here's the func:

class func display(from sourcevc:UIViewController){
    let vc=UINib(nibName: "FullscreenGalleryVC", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FullscreenGalleryVC
    sourcevc.present(vc, animated: true, completion: nil)
}

I get this error:

could not dequeue a view of kind: UICollectionElementKindCell with identifier fullscreen_cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard


It works fine if I put the custom cell in another xib file and call register(nibClass, forCellWithReuseIdentifier: cellId).

It works fine if I don't put this FullScreenGalleryVC class in a separate xib file (and keep it in my main storyboard).


But I use this class from both the app and an action extension so that's why I'd like to use a common file instead of duplicating everything. Is there a way to do that or do I imperatively have to put the custom cell in a different xib file to make it work?

enter image description here

Upvotes: 0

Views: 1077

Answers (1)

Bappaditya
Bappaditya

Reputation: 9652

If you a xib file for FullScreenGalleryVC controller then you should use register(nibClass, forCellWithReuseIdentifier: cellId) to tell the collection view how to create a new cell of the given type.

let cellNib = UINib(nibName: "FullScreenGalleryCell", bundle: .main) 
collectionView.register(cellNib, forCellWithReuseIdentifier: "fullscreen_cell")

If you use a storyboard, then it's already known to the collection view with the specified cellId.

In my opinion, you can use a storyboard for FullScreenGalleryVC and reuse the same for other classes.

Present a viewController from a specific storyboard like,

let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "storyboardId")
self.present(controller, animated: true, completion: nil)

image 1image 2

Upvotes: 1

Related Questions