细胞中的约束受损

时间:2018-05-19 16:30:33

标签: ios swift nslayoutconstraint

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

我正在尝试在运行时更改此backView的高度和宽度,但我得到的是一堆像这样的Autolayout错误:

  

[LayoutConstraints]无法同时满足约束。将试图通过打破约束来恢复......

我为这个单元格创建了SimpleTextCell类,它的init看起来像这样:

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

但它也不起作用。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题出在这里

 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