如何为自定义 table 视图单元动态设置约束?

How to dynamically set constraints for a custom table view cell?

我有一个具有以下约束的自定义 table 视图单元格,一个用于 UILabel,一个用于 UIImageView

var titleLabel = UILabel()
var imageView = UIImageView()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    addSubview(titleLabel)
    
    setTitlelabelConstraints()
    setImageConstraints()
}

func setTitlelabelConstraints() {
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    titleLabel.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 20).isActive = true
    titleLabel.heightAnchor.constraint(equalToConstant: 55).isActive = true
    titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12).isActive = true
}

func setImageConstraints() {
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 55).isActive = true
    imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 16/9).isActive = true
}

如何有条件地将前导锚点设置为 0,以便在没有图像时文本标签占据整个单元格?如果没有图像,静态约束当前会留空 space。

您可以这样做:将图像视图宽度约束设为 less-than-or-equal 约束,并添加另一个图像视图宽度约束,其常量为 0,优先级为 700。

但是,这并不能真正解决您的问题。毕竟,图像视图和标签之间仍然有间距。 真正的答案在于您自己的话:“静态”。不要让它们静止!根据是否有图像更改约束。毕竟,你知道,对于每个单元格,是否有图像,所以这都是你配置的一部分。

约束是 full-fledged 对象,因此当您制作图像视图宽度约束和标签前导约束时,请保留对它们的引用,现在您只需将宽度设置为 0,将间距设置为 0没有图像。

在这个截屏视频中,我所做的只是 removing/adding 图像和更改常量。我添加动画只是为了好玩,但你当然不会那样做。