Search code examples
iosswift3uicollectionviewxcode8uicollectionviewcell

How to programmatically add a UILabel to UICollectionViewCell in Swift 3


I have a few UICollectionViewCells and I want to add two labels to the cells programmatically. How would I do this the correct way?


Solution

  • In your cell class define it global.

    class YourCollectionViewCell: UICollectionViewCell {
    
            var titleLabel:UILabel = {
                let label = UILabel(frame: CGRect(x:100, y: 30, width: UIScreen.main.bounds.width , height: 40))
                label.textAlignment = .left
                label.lineBreakMode = .byWordWrapping
                label.numberOfLines = 0
                return label
            }()
    
            override init(frame: CGRect) {
                super.init(frame: frame)
                self.addSubview(self.titleLabel)
            }
    }