首页 > 解决方案 > prepareForInterfaceBuilder 中的约束?

问题描述

我不是 的忠实粉丝@IBDesignable,但在玩弄它时,我发现如果在 中添加子视图,则会添加子视图prepareForInterfaceBuilder,但不会遵守您应用到它的约束。

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

标签: iosinterface-builderibdesignable

解决方案


确保在添加子视图时将prepareForInterfaceBuildertranslatesAutoresizingMaskIntoConstraints属性设置为false是否要对其使用约束并使其在 Interface Builder 中正确显示。如:

@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 中没有任何内容)。


推荐阅读