通过自动布局以编程方式设置UITableViewCell高度

时间:2019-06-06 08:39:05

标签: swift autolayout

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

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)找到添加了不必要约束的代码   或约束并修复它。 (       ”   (活动)>“,       ”   (活动)>“)

     

将尝试通过打破约束来恢复      (活动)>

1 个答案:

答案 0 :(得分:0)

通过添加辅助视图来解决此问题:

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