UICollectionView's cell registerClass in Swift

IosSwiftUitableview

Ios Problem Overview


Right now I'm using NSClassFromString, but is there a better way to get an AnyClass! from a class in Swift? I am trying to pass the reference to my collection view's -registerClass:forCellWithReuseIdentifier: method.

collectionView.registerClass(NSClassFromString("MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")

Ios Solutions


Solution 1 - Ios

This is currently just a blind but educated guess, but using Class.self might be what you want.

collectionView.registerClass(MyCoolViewCell.self, forCellWithReuseIdentifier: "MyCoolViewCell")

Solution 2 - Ios

In case you are using a nib file, use this code instead:

    let nib = UINib(nibName: "MyCoolViewCell", bundle: nil)
    collectionView?.register(nib, forCellWithReuseIdentifier: "MyCoolViewCellIdentifier")

Solution 3 - Ios

In Swift 3:

self.collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "CustomCollectionViewCellReuseIdentifier")

Solution 4 - Ios

NSClassFromString("MyCoolViewCell")might get nil.
Should add module name in prefix:
collectionView.registerClass(NSClassFromString("MyApp.MyCoolViewCell"), forCellWithReuseIdentifier: "MyCoolViewCell")

If cellClass not a variable, use MyCoolViewCell.self is a better choice.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjarjarView Question on Stackoverflow
Solution 1 - IosMatthias BauchView Answer on Stackoverflow
Solution 2 - IosatulkhatriView Answer on Stackoverflow
Solution 3 - IosMaria OrtegaView Answer on Stackoverflow
Solution 4 - IosyhlinView Answer on Stackoverflow