[英]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. 我有几个UICollectionViewCells,我想以编程方式向单元格添加两个标签。 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
您可以使用关键字google: customize table view cell
This is how you can do it: 这是你如何做到的:
Firstly, You need to create a subclass of UICollectionViewCell
like so: 首先,您需要创建一个UICollectionViewCell
的子类, UICollectionViewCell
所示:
// I'll use YourCellClass
as your custom cell's class
//我将使用YourCellClass
作为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. 然后设置表视图的datasource
。 And in tableView:cellForRowAtIndexPath
add following code to get instance of your cell Class and return it for your table view row 并在tableView:cellForRowAtIndexPath
添加以下代码以获取您的单元格类的实例并将其返回给您的表视图行
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.