[英]How to programmatically add an UILabel to my UICollectionViewCell
[英]How to programmatically add a UILabel to UICollectionViewCell in Swift 3
我有几个UICollectionViewCells,我想以编程方式向单元格添加两个标签。 我怎么能以正确的方式做到这一点?
在您的单元类中,将其定义为全局。
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)
}
}
您可以使用关键字google: customize table view cell
这是你如何做到的:
首先,您需要创建一个UICollectionViewCell
的子类, UICollectionViewCell
所示:
//我将使用YourCellClass
作为custom cell's class
class YourCellClass: UITableViewCell {
// Your can add your label to this Cell
// Review @Özgür Ersil's code above
}
然后,您必须将此类注册到表视图。 该类必须具有标识符
tableView.register(YourCellClass.self, forCellReuseIdentifier: "cellId")
然后设置表视图的datasource
。 并在tableView:cellForRowAtIndexPath
添加以下代码以获取您的单元格类的实例并将其返回给您的表视图行
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! YourCellClass
return cell
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.