故事板中具有动态高度的自定义视图的高度约束

Height contraint in storyboard for a custom view with dynamic height

从这里开始 swift...如何将约束高度设置为自定义视图以包裹内容或换句话说具有动态高度?

在Android中我们使用包装内容或匹配父级高度。 ios 的匹配父等效项是将顶部、底部、左侧、右侧约束设置为 0(如果我理解得很好的话)但是包装内容呢?

大多数时候自定义视图高度可以是动态的。当我从情节提要中拖出一个视图来扩展我的自定义视图时,我被要求设置高度限制...求助!

已编辑:为什么有人在没有任何理由的情况下输入 -1,这是一个愚蠢的问题吗?!

第一步是确保您已正确配置自定义 @IBDesignable 视图。

这是一个简单的例子,有一个UITextField和一个"helper"UILabel

文本视图设置为 non-scrolling -- 这允许它根据文本 auto-size 自己的高度。它会随着您键入和添加/删除文本而增大/缩小。

文本视图和标签被添加到垂直 UIStackView 中,使其真正非常容易布局:

@IBDesignable
class MyCustomView: UIView {

    let theTextView: UITextView = {
        let v = UITextView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.isScrollEnabled = false
        return v
    }()

    let helperLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.textColor = .white
        v.backgroundColor = .blue
        v.text = "Helper Text"
        return v
    }()

    let theStackView: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.alignment = .fill
        v.distribution = .fill
        v.spacing = 8
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {

        // add the stack view as a subview
        addSubview(theStackView)

        // constrain the stack view top / bottom / leading / trailing
        // with 8-pts "padding" on each side
        NSLayoutConstraint.activate([

            theStackView.topAnchor.constraint(equalTo: topAnchor, constant: 8.0),
            theStackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8.0),

            theStackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            theStackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),

            ])

        // add the text view and label to the stack view
        theStackView.addArrangedSubview(theTextView)
        theStackView.addArrangedSubview(helperLabel)

    }

}

现在,在 Storyboard 的新视图控制器中,添加一个普通的 UIView 并给它一个背景颜色(这样我们就可以看到它)。添加 40 的 Leading 和 Trailing 约束,并添加 Center Vertically 约束。它看起来应该类似于:

Storyboard 会告诉你它需要一个约束:

选择视图后,转到 Identity Inspector 并将 Class 更改为 MyCustomClass。如果您打开了 **Automatically Refresh Views`,它应该更改为:

它现在垂直居中,并使用自己的高度(由嵌入在堆栈视图中的文本视图和标签的固有高度决定)。不再 Needs constraints for: Y position or height 错误消息,无需设置任何额外的约束。

当您 运行 应用程序(并在文本视图中输入一些文本)时,您将得到: