我有一个自定义集合视频类,其中包含标签和图像。基本上,图像将被约束在单元格的左侧,顶部和右侧。但是,我希望它的高度取决于Uilabel的高度,这反过来将取决于其中的内容。以下是我的尝试:
导入Uikit
类CustomCollectionViewCell:UicollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .yellow
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(cellTextTile text: String) {
self.init()
}
func setupCustomCellElements(cellImageName image: String, cellTitleTextColour textColour: UIColor, cellTitleTextSize textSize: CGFloat, cellTitleFontType fontType: String, cellTitle title: String) {
let cellImage: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = .clear
imageView.image = UIImage(named: image)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let cellTitle: UILabel = {
let label = UILabel()
label.textColor = textColour
label.font = UIFont(name: fontType, size: textSize)
label.text = title
label.textAlignment = .center
label.frame.size = CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
addSubview(cellImage)
addSubview(cellTitle)
NSLayoutConstraint.activate([
cellTitle.bottomAnchor.constraint(equalTo: bottomAnchor),
cellTitle.leftAnchor.constraint(equalTo: leftAnchor),
cellTitle.rightAnchor.constraint(equalTo: rightAnchor),
cellImage.bottomAnchor.constraint(equalTo: cellTitle.topAnchor),
cellImage.topAnchor.constraint(equalTo: topAnchor),
cellImage.leftAnchor.constraint(equalTo: leftAnchor),
cellImage.rightAnchor.constraint(equalTo: rightAnchor)
])
}
}
但是,对于上述代码,我没有得到我想要的那种行为。我希望Uilabel的高度根据其内容更改。然后,图像的高度相应调整?
问候,shadi。
您需要对ImageView的高度约束
cellImage.heightAnchor.constraint(equalToConstant: 50), // or any value
也不要添加方法中的属性setupCustomCellElements
使其成为实例变量,而是在init
函数中添加它们
最好还将视图添加到
contentView.addSubview(cellImage)
contentView.addSubview(cellTitle)
并用它约束约束