我有几个UICollectionViewCells,我想通过编程方式向这些单元格添加两个标签。正确的方法是什么?
我有几个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)
}
}
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