2016-09-06 63 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() 

}