rideintothesun rideintothesun - 4 years ago 148
iOS Question

Text not being set in UILabel (or UITextField) in a UICollectionViewCell

I'm doing something too stupidly obvious to see for myself, so hopefully a peer review will help.

I've got the simplest UICollectionViewController setup. I have a custom UIViewControllerCell which contains a UILabel.

The data to populate the UICollectionViewController is just a static array.

When I run the app, the UICollectionViewController is displayed, but only shows the default label text e.g. 'Label'.

So I think the majority of the code is correct, its just that I cannot set the text in the UILabel.

Its something very obvious I'm sure but I just can't see it

Here is some of the code

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WrappedCollectionViewCell

// Configure the cell
var myLabel = UILabel()
cell.brandText = myLabel
var labelString:String = brandList[indexPath.row]
cell.brandText.text = labelString

return cell
}


All the data is correct I can see the correct text and the correct indexPath. But if I debug in Xcode at the end of the method I can see it still shows the text as 'Label'

Here is my custom UICollectionViewController. All I did was set up the outlet.

import UIKit

class WrappedCollectionViewCell: UICollectionViewCell {

// Previously wrong because this was set to be a UITextField
@IBOutlet weak var brandText: UILabel!
}


So please help, I've spent hours on this, it's driving me mad!

Answer Source

You are declaring new object of UILabel no need for these 2 lines (you made a mistake beacuse you connected textfield not label in your cell class):

var myLabel = UILabel()
cell.brandText = myLabel 

First you need to connect proper ui component to your cell(@IBOutlet weak var brandText: UILabel) and then just set the text of your label in cell like this:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WrappedCollectionViewCell

    // Configure the cell

    var labelString:String =  brandList[indexPath.row]
    cell.brandText.text = labelString

    return cell
}

And you should be good to go!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download