seanbehan
seanbehan

Reputation: 1621

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.

Upvotes: 0

Views: 561

Answers (2)

Imad Ali
Imad Ali

Reputation: 3301

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!

Upvotes: 2

Guy Kidron
Guy Kidron

Reputation: 1

UICollectionView does not have ready made cell templates like UITableView. You will have to create your own class of UICollectionViewCell.

Upvotes: 0

Related Questions