IBDesignable并通过IBInspectable属性更新内部自动布局约束

时间:2018-10-16 20:42:19

标签: ios xcode autolayout interface-builder ibdesignable

我有一个带有一个@IBInspectable属性leftMargin的IBDesignable UIView。该视图包含一个子视图contentViewcontentView帧由自动版式控制。通过控制Interface Builder中的leftMargin属性,我想了解我的内部自动布局(在self视图和contentView之间)的约束是如何变化的。我有这么简单的代码,但是我不知道该怎么做。我只是从这个问题的非常复杂的示例中提取了用例。这是代码:

import UIKit

@IBDesignable class LayoutConstraintsDemoView: UIView {

    @IBInspectable var leftMargin: CGFloat = 16.0 {
        didSet {
            self.updateMargins()
        }
    }

    lazy var contentView: UIView = self.lazyContentView()
    var leadingConstraint: NSLayoutConstraint? = nil

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.selfInit()
    }

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

    override func prepareForInterfaceBuilder() {
        self.leftMargin = 8.0
    }

    private func selfInit() {
        backgroundColor = .yellow
        addSubview(contentView)

        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.trailingAnchor.constraint(equalTo: trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])

        self.leadingConstraint = contentView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: self.leftMargin)
        self.leadingConstraint?.isActive = true
    }

    fileprivate func lazyContentView() -> UIView {
        let view = UIView(frame: CGRect.zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red
        return view
    }

    func updateMargins() {
        self.leadingConstraint?.constant = self.leftMargin
        setNeedsLayout()
        layoutIfNeeded()
    }

}

在界面构建器中,我可以更改leftMargin,但是我的视图AutoLayout根本没有更新。所以我有这样的问题:

  1. 如何更改leftMargin以更新自定义视图的布局?
  2. 如何为Interface Builder内部contentView公开,以便将内容放入Interface Builder的此视图中。目前,我只看到外部UIView。我的意思是Visual Effect View这样的东西有内部View。我想访问我的内部red contentView,以便可以在Interface Builder中填充对象。

enter image description here

0 个答案:

没有答案