uicollectionviewcell 添加 label
在 UICollectionViewCell 中添加 UILabel 的步骤如下:
-
在 UICollectionViewCell 的子类中声明一个 UILabel 实例;
-
在 UICollectionViewCell 的 init 方法中,初始化 UILabel 实例并添加到 UICollectionViewCell 中;
-
在 UICollectionViewCell 的 layoutSubviews 方法中,设置 UILabel 实例的 frame 和其他属性。
下面是一个示例代码:
class MyCollectionViewCell: UICollectionViewCell {
var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 16)
contentView.addSubview(titleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = contentView.bounds
}
}
在使用该 UICollectionViewCell 时,可以通过 titleLabel 属性设置 UILabel 的文本内容和其他属性:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath) as! MyCollectionViewCell
cell.titleLabel.text = "Hello, World!"
原文地址: https://www.cveoy.top/t/topic/bE5T 著作权归作者所有。请勿转载和采集!