prepareForInterfaceBuilder 中的约束?

constraints in prepareForInterfaceBuilder?

我不是 @IBDesignable 的忠实粉丝,但在使用它的过程中我发现,如果您在 prepareForInterfaceBuilder 中添加子视图,则会添加子视图,但会对其应用约束不服从。

这是 prepareForInterfaceBuilder 的已知限制吗?那是有道理的;我想这种方法应该仅限于做一些事情,比如给标签一些虚拟文本。

如果要在 prepareForInterfaceBuilder 中添加子视图,请确保将其 translatesAutoresizingMaskIntoConstraints 属性 设置为 false 并显示它在界面生成器中正确。如:

@IBDesignable class View: UIView {
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        let subview = UIView()

        // Make sure to set this to false!
        subview.translatesAutoresizingMaskIntoConstraints = false

        // Just setting the background color so it can be seen in IB.
        subview.backgroundColor = .blue

        // Must add it as a subview before activating any constraints.
        addSubview(subview)

        // Adding some example constraints with some padding to make sure they're behaving properly.
        NSLayoutConstraint.activate(
            [subview.topAnchor.constraint(equalTo: topAnchor, constant: 20),
             subview.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
             subview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20),
             subview.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20)]
        )
    }
}

这是一个很容易犯的错误,因为 Xcode(撰写此答案时为 10.3)不会向您提供有关 IBDesignable 渲染期间布局引擎发生的情况的任何反馈(无控制台日志)消息,Interface Builder 中没有错误,Report Navigator 中没有任何内容)。