首页 > 解决方案 > 带有文本的标签未显示在自定义单元格中

问题描述

我为 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
     }

任何想法我哪里出错了?

标签: swiftuicollectionviewcell

解决方案


尝试

titleLabel.translatesAutoresizingMaskIntoConstraints = false

推荐阅读