以编程方式在集合视图单元格中设置标签约束的高度

Setting up height of label constraint in collectionview cell programatically

我正在尝试为 collectionview cell

中的标签设置高度限制
   class CollectionViewCell: UICollectionViewCell {

   @IBOutlet weak var label: UILabel!
   override func layoutSubviews() {
   super.layoutSubviews()
      constraint()
    }
   func constraint() {

        label.addConstraint(NSLayoutConstraint(item:label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 25))
    }
}

我做了上面的操作,但没有用。 layoutSubviews 声明在这里有效吗?

NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .Equal, toItem: label, attribute:.Height, multiplier: 1.0, constant:25.0)

NSLayoutConstraint.constraintsWithVisualFormat(@"V:[label(==24)]", options: nil , metrics: nil, views: NSDictionaryOfVariableBindings(label))

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html

(...)you must specify a value for each parameter, even if it doesn’t affect the layout. The end result is a considerable amount of boilerplate code, which is usually harder to read. (...)

有一种方便的方法可以使用约束并在代码中更改它。

首先,声明一个约束属性:

@IBOutlet weak var labelHeight: NSLayoutConstraint!

其次,在XIB或者Stroyboard中绑定:

最后,您可以通过编程方式更改它:

self.labelHeight.constant = 130