如何以编程方式为视图设置动态高度?

时间:2018-11-21 22:00:32

标签: ios swift nslayoutconstraint

我正在使用继承自UIView class MyView: UIView {

的类来创建自己的类

这个想法是创建一个视图并在其中放置一些标签。我是通过以下方式实现的:

init() {
    super.init(frame: CGRect(x: 8.0, y: 104.0, width: UIScreen.main.bounds.width - 16.0, height: 60.0))
    initialize()
}

其中

fileprivate func initialize() {        
    label = UILabel()
    label.numberOfLines = 0
    label = UILabel(frame: CGRect(x: 16.0, y: 8.0, width: self.frame.width - 32.0, height: self.frame.height - 16.0))
    self.addSubview(label)
}

,现在一切正常。 但是现在我想使此自定义视图的高度动态化,因此视图的高度将取决于其中标签的高度(文本)。

我尝试添加:

let constraints = [
        NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0),
        NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0),
        NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 8.0),
        NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 8.0)]

    label.addConstraints(constraints)

self.translatesAutoresizingMaskIntoConstraints = false
    self.heightAnchor.constraint(greaterThanOrEqualToConstant: 60.0).isActive = true

最终,我在日志中遇到了一个巨大的错误:

The view hierarchy is not prepared for the constraint
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.

有人可以帮助我解决这个问题吗? 我已经用谷歌搜索了,但是找不到任何可以帮助我解决问题的东西。 也许我的布局错误。 感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题自

label.addConstraints(constraints)

您在父标签和标签之间添加了约束,这是不正确的,您需要将其添加到父标签中

self.addConstraints(constraints)

另一个苹果推荐的方法是

NSLayoutConstraint.activate([constraints])

哪个会为您处理


let mmmview = MyView()
mmmview.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mmmview)
let constraints = [
    NSLayoutConstraint(item: mmmview , attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 8.0),
    NSLayoutConstraint(item: mmmview , attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 8.0),
    NSLayoutConstraint(item: mmmview , attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 8.0)
 ]
 NSLayoutConstraint.activate(constraints)