2016-09-06 62 views
4

我很好奇为什么这不会将backgroundColor设置为红色?@IBDesignable视图不会在界面生成器内绘制背景色

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

这就是结果。

enter image description here

而这正是我希望它看起来像。

enter image description here

回答

8

在接口构建器(IB)呈现,其在自定义用户界面元素的IB设置的属性被调用init后加载。用于设置initbackgroundColor的代码正在调用中。但在此之后,它再次将backgroundColor设置为IB中的值backgroundColor

我找不到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() 
    } 
} 

现在,把断点放在所有的方法中。然后,在Interface Builder中选择CustomLabel的对象,然后选择编辑器→调试选定的视图。

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

可能您了解这一点,但为了清楚起见,您可以使用以下内容在IB中进行反映。

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

}