Search code examples
iosuicollectionviewstoryboarduicollectionviewcell

How do you add a UILabel to a UICollectionViewCell without custom class?


I've dragged a UICollectionViewController to the main storyboard and created the corresponding class.

enter image description here I've named/connected everything in storyboard and view controller correctly.

enter image description here enter image description here

But I am unable to access objects I've placed in the UICollectionViewCell... for instance I can't set the text property on the UILabel.

enter image description here

If I create a custom UICollectionViewCell class and create/connect the @IBOutlet to the UILabel everything works fine.

But do I have to create this custom UICollectionViewCell class?

It looks like the collection view is aware that a label has been added to the cell, based on the tree view in storyboard.

I just want to add a label w/ some default text and want to avoid adding the extra file.


Solution

  • You can do even without creating the custom class, by using the 'Tag'

    For example, give the Tag '101' to your UICollectionView label as shown below.

    Then in your cellForRowAt method:

    let label = cell.viewWithTag(101) as! UILabel
    label.text = "Hi"
    

    enter image description here

    Hope it helps!