swift - 带有文本的标签未显示在自定义单元格中
问题描述
我为 UICollectionView 设置了一个自定义单元格。我有一个具有图像和标题的数据模型。
我可以让图像显示在单元格中,但不能让表格显示
我尝试在自定义单元格内以编程方式设置标签(与设置图像的方式相同)但图像显示但标签不可见......
class CustomCell: UICollectionViewCell {
var data: CustomData? {
didSet {
guard let data = data else {return}
bg.image = data.image
titleLabel.text = data.title
}
}
fileprivate var titleLabel : UILabel = {
let label = UILabel()
label.textAlignment = .left
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 1
label.textColor = .black
label.font = UIFont (name: "Helvetica Neue", size: 30)
label.text = "random text"
return label
}()
fileprivate let bg : UIImageView = {
let iv = UIImageView()
iv.image = #imageLiteral(resourceName: "pic1")
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.layer.cornerRadius = 12
iv.layer.masksToBounds = true
iv.clipsToBounds = true
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(bg)
bg.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
bg.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
bg.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
bg.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是自定义单元格的设置方式,下面是 cellForItemAt 的设置方式
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
let color = colorList[indexPath.row]
cell.backgroundColor = color
cell.contentView.layer.masksToBounds = true;
cell.layer.cornerRadius = 12
cell.clipsToBounds = true
return cell
}
任何想法我哪里出错了?
解决方案
尝试
titleLabel.translatesAutoresizingMaskIntoConstraints = false
推荐阅读
- reactjs - 为什么要使用高阶组件
- c++ - QFrame 没有在垂直滚动条下绘制
- vb6 - 与 COM 对象 (flexgrid) 的后期绑定比早期绑定慢 2 倍
- c# - vs c# Publish 没有注册我的 .dll
- ruby-on-rails - 如何使用 Open/Closed 原则或策略模式重构此 ruby 代码
- python-3.x - python设置取两个文件之间名称值的差异
- asp.net - 如何上传和检索 PDF 文件
- jquery - 用于多个下拉的自定义 CSS
- java - myEclipse 首选项没有 Maven 选项
- javascript - 单击输入以选择图像然后显示按钮后如何调用函数?