Martin Muldoon
Martin Muldoon

Reputation: 3436

Programmatically add a UILabel to a UICollectionViewCell

I have a UICollectionView that presents images in a waterfall type layout, which works perfectly. I'm now trying to add a description over each image. The challenge is I'm trying to add the UILabel programmatically, but it is not appearing. I'm certain label.text contains text.

class NTWaterfallViewCell :UICollectionViewCell, NTTansitionWaterfallGridViewProtocol{

    var photoName = ""
    var imageName : String?

    var imageViewContent : UIImageView = UIImageView()
    var label:UILabel = UILabel()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.lightGray
        contentView.addSubview(imageViewContent)
        contentView.addSubview(label)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        imageViewContent.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
        imageViewContent.loadImageWithURL(imageName!)

        label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
        label.center = CGPoint(x: 160, y: 285)
        label.textAlignment = .center
        label.text = photoName
    }

Upvotes: 1

Views: 296

Answers (1)

Gereon
Gereon

Reputation: 17882

You're creating two UILabel instances in your code - the first is at var label: UILabel = UILabel(), and this one gets added to your contentView in init.

Later, you're overwriting self.label with a new instance, in your layoutSubViews(), but this new instance is never added to the contentView.

Rearrange you code so that only one instance is created and added.

Upvotes: 1

Related Questions