简体   繁体   中英

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?

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)
        }
}

You can google with keyword: customize table view cell

This is how you can do it:

Firstly, You need to create a subclass of UICollectionViewCell like so:

// I'll use YourCellClass as your custom cell's class

class YourCellClass: UITableViewCell {
// Your can add your label to this Cell
// Review @Özgür Ersil's code above
}

Then, you have to register this class to your table view. This class must have a Identifier

tableView.register(YourCellClass.self, forCellReuseIdentifier: "cellId")

then set datasource of your table view. And in tableView:cellForRowAtIndexPath add following code to get instance of your cell Class and return it for your table view row

let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM