@IBDesignable does not display background color inside Interface Builder

I am curious why this is not setting backgroundColorin red?

@IBDesignable class CustomLabel: UIView {

  let view = UIView()

  func setup() {
    backgroundColor = UIColor.red
    view.backgroundColor = UIColor.green
    view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    addSubview(view)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
  }
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
  }
}

This is the result.

enter image description here

And this is what I expect it to look like.

enter image description here

+4
source share
1 answer

When rendering in the Interface Builder (IB), the properties that are set to IB in the user interface of the user interface are loaded after the call init. Your installation code backgroundColoris initinvoked. But after that, he again sets the backgroundColorvalue backgroundColorto IB.

Apple . , . .

@IBDesignable class CustomLabel: UIView {

    let view = UIView()

    override var backgroundColor: UIColor? {
        didSet {
            print("here: "); // break point 1
        }
    }

    func setup() {
        self.backgroundColor = UIColor.redColor()  // break point 2
        view.backgroundColor = UIColor.greenColor()
        view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        addSubview(view)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)  // break point 3
        setup()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)  // break point 4
        setup()
    }
}

. CustomLabel Interface Builder "" ➔ " ".

. , , .

, , , IB.

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    backgroundColor = UIColor.grayColor()

}
+9

Source: https://habr.com/ru/post/1653778/


All Articles