单元格中的破坏约束

Broken constraints in the cell

我需要在我的单元格中显示一些 UIView,但是这个 UIView (backView) 的大小对于每个单元格都是不同的。所以我也需要改变这个单元格的高度。

我试图在 运行 时间内更改此 backView 的高度和宽度,但我得到的只是一堆类似这样的自动布局错误:

[LayoutConstraints] Unable to simultaneously satisfy constraints. Will attempt to recover by breaking constraint...

我为这个单元格创建了 SimpleTextCell class,它的初始化看起来像这样:

self.backView = UIView()
self.backView.translatesAutoresizingMaskIntoConstraints = false
self.backView.backgroundColor = UIColor.yellow
self.backView.layer.cornerRadius = 8.0
self.contentView.addSubview(backView)

let constraintBackViewTop = NSLayoutConstraint(item: backView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: -5)
let constraintBackViewBottom = NSLayoutConstraint(item: backView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottomMargin, multiplier: 1.0, constant: 5)
let constraintBackViewLeft = NSLayoutConstraint(item: backView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .leftMargin, multiplier: 1.0, constant: 0)
constraintBackHeight = NSLayoutConstraint(item: backView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: superHeight)
constraintBackWidth = NSLayoutConstraint(item: backView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: superWidth)

self.contentView.addConstraints([constraintBackViewTop, constraintBackViewBottom, constraintBackViewLeft, constraintBackHeight, constraintBackWidth])

superHeightsuperWidth只是这里的一些默认值。

我的cellForRowAt函数是这样的:

let cell = tableView.dequeueReusableCell(withIdentifier: "simpleTextCell", for: indexPath) as! SimpleTextCell

cell.selectionStyle = .none
cell.backgroundColor = UIColor.red
cell.constraintBackHeight.constant = 100
cell.constraintBackWidth.constant = 200
cell.updateConstraints()

而且根本不起作用。我有错误(就像我之前提到的那样),虽然我的单元格的高度有点正确,但我的 backView 是不可见的,因为 backView.frame 的宽度为零(我没有一个线索为什么)和 backView 的高度是 100(相同)。似乎忽略了我的新约束。

我已尝试在 cellForRowAt 中为这些约束设置优先级:

cell.constraintBackHeight.priority = UILayoutPriority.init(rawValue: 999)

结果是运行-时间错误。

我试图通过这样的方法来克服这个错误:

cell.constraintBackHeight.isActive = false
cell.constraintBackHeight.priority = UILayoutPriority.init(rawValue: 999)
cell.constraintBackHeight.isActive = true

但是也没用。

我该如何解决这个问题?

问题就在这里

 constraintBackHeight = NSLayoutConstraint(item: backView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: superHeight)
 constraintBackWidth = NSLayoutConstraint(item: backView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: superWidth)

您正在设置 2 个高度限制,可能是您只是复制为宽度而忘记将其更改为 .width