@IBDesignable视图未在Interface Builder中绘制背景颜色 [英] @IBDesignable view doesn't draw background color inside Interface Builder

查看:96
本文介绍了@IBDesignable视图未在Interface Builder中绘制背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么不将backgroundColor设置为红色?

I'm curious why doesn't this set the backgroundColor to 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()
  }
}

这是结果.

这就是我期望的样子.

推荐答案

在界面"生成器(IB)中进行渲染时,在调用init之后,将加载在自定义UI元素的IB中设置的属性.在init中设置backgroundColor的代码正在被调用.但是之后,它将再次为IB中的backgroundColor值设置backgroundColor.

While rendering in Interface builder(IB), the properties which are set in IB of custom UI element are loaded after the call to init. Your code for setting the backgroundColor in init is getting called. But after that, it again sets the backgroundColor for the value of backgroundColor in IB.

我找不到与此有关的Apple文档.我说这是基于以下分析.我对您的代码做了一些修改以进行调试.

I could not find the Apple documentation for this. I am saying this based on following analysis. I modified your code a little for debugging.

@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()
    }
}

现在,将断点放在所有方法中.然后,在Interface Builder中选择CustomLabel的对象,然后选择Editor➔Debug Selected Views.

Now, put the breakpoints in all methods. Then, select the object of CustomLabel in Interface Builder, and choose Editor ➔ Debug Selected Views.

您可以看到方法调用的顺序.这只是显示了界面构建器中的渲染顺序,而不是它在运行时可能遵循的顺序.

You can see the sequence of method calls. This just shows the sequence of rendering in interface builder, not the sequence it may follow in run time.

也许您知道这一点,但是为了清楚起见,您可以使用以下内容在IB中反映这一点.

May be you know this, but for the sake of clarity, you can use following to reflect this in IB.

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

}

这篇关于@IBDesignable视图未在Interface Builder中绘制背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆