Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView's cell registerClass in Swift

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") 
like image 984
jarjar Avatar asked Jun 08 '14 21:06

jarjar


People also ask

How do I register a collection view cell?

Use a cell registration to register cells with your collection view and configure each cell for display. You create a cell registration with your cell type and data item type as the registration's generic parameters, passing in a registration handler to configure the cell.


2 Answers

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

collectionView.registerClass(MyCoolViewCell.self, forCellWithReuseIdentifier: "MyCoolViewCell") 
like image 157
Matthias Bauch Avatar answered Oct 06 '22 12:10

Matthias Bauch


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

    let nib = UINib(nibName: "MyCoolViewCell", bundle: nil)     collectionView?.register(nib, forCellWithReuseIdentifier: "MyCoolViewCellIdentifier") 
like image 20
atulkhatri Avatar answered Oct 06 '22 12:10

atulkhatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!