Designing a UICollectionViewCell in a Storyboard

I never used UICollectionViewController s, and I thought they were somewhat similar to UITableViewController s, but, to my surprise, I cannot add user interface elements to my UICollectionViewCell in the same way as with custom UITableViewCell s.

In fact, I can add tags, buttons, etc. to the interface builder, but when I run the application, the cells appear empty.

I registered the cell class during the viewDidLoad method by calling (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier , and I verified that I was returning a valid instance of UICollectionViewCell in the (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath .

What am I doing wrong?

+7
ios objective-c uicollectionview uicollectionviewcell
source share
1 answer

My full explanation is here .

Create a custom class for the UICollectionViewCell:

 import UIKit class MyCollectionViewCell: UICollectionViewCell { // have outlets for any views in your storyboard cell @IBOutlet weak var myLabel: UILabel! } 

In a storyboard, make a cell using this class

enter image description here

And set cell id

enter image description here

Do not use registerClass...forCellWithReuseIdentifier in viewDidLoad . But you will refer to it in collectionView...cellForItemAtIndexPath :

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // get a reference to our storyboard cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell // Use the outlet in our custom class to get a reference to the UILabel in the cell cell.myLabel.text = self.items[indexPath.item] cell.backgroundColor = UIColor.yellowColor() return cell } 

Connect the exits from the views in the storyboard cell to the MyCollectionViewCell class.

+10
source share

All Articles