使用自动布局以编程方式设置 UITableViewCell 高度



我想通过自动布局设置我的单元格高度,这是代码:

class AccountsBalanceResidueCell : BaseCell {
    private let title: UILabel = {
        let lbl = LabelSL.italicLarge()
        lbl.text = Strings.Common.accountsResidue.value
        return lbl
    }()
    private let amount: UILabel = LabelSL.italicLarge()
    func setup(_ amount: String) {
        self.amount.text = amount + " " + Strings.Common.roubleSymbol.value
    }
    override func prepare() {
        contentView.backgroundColor = .cyan
        contentView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(title)
        addSubview(amount)
        setConstraints()
    }
    private func setConstraints(){
        let height: CGFloat = UIScreen.main.bounds.size.height * 0.3333
        contentView.heightAnchor.constraint(equalToConstant: height).isActive = true
    }
}

但是,我在日志中收到错误:

无法同时满足约束。 可能至少有一个 以下列表中的约束是你不需要的约束。 尝试 这:(1(查看每个约束并尝试找出哪些约束 不要指望; (2( 查找添加不需要的约束的代码 或约束并修复它。 ( " (活动(>", " (活动(>" (

将尝试通过打破约束进行恢复 (活动(>

确实通过添加辅助视图解决了这个问题:

private let container: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .clear
    return view
  }()
container.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    container.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
    container.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
    container.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
    let heightConstraint = container.heightAnchor.constraint(equalToConstant: height)
    heightConstraint.priority = UILayoutPriority(rawValue: 751)
    heightConstraint.isActive = true

最新更新