2015-11-19 26 views
0

我有一個UIButton從自定義類ColorButton繼承。從自定義類更新按鈕屬性

@IBDesignable 
class ColorButton: UIButton { 

    @IBInspectable 
    var buttonColor: UIColor? 


    override func drawRect(rect: CGRect) { 

     let path = UIBezierPath(ovalInRect: rect) 
     buttonColor?.setFill() 
     path.fill() 
    } 

} 

我能夠初步設置按鈕的顏色,但是當我嘗試使用以下方法更改它時,沒有任何更改。

myButton.buttonColor = UIColor.blueColor() 

我相信我只是更新了屬性,但我需要重新繪製按鈕才能看到新的顏色。我不確定最好的方法來做到這一點。

+0

我想你應該重寫ColorButton類buttonColor屬性爲好。 – msmq

回答

1

現在你只有財產,當你設置它什麼都不做。您需要設置backgroundColor parrent類屬性(這是UIButton財產在你的情況)來解決這個問題:

@IBDesignable 
class ColorButton: UIButton { 

    @IBInspectable 
    var buttonColor: UIColor? { 
     get { 
      return self.buttonColor 
     } 
     set { 
      self.backgroundColor = newValue 
     } 
    } 
} 

但在你的例子中,你不需要創建自定義類的。你可以從普通UIButton對象中調用backgroundColor對象,如果你得到的只是這個功能

+0

是的你的權利。我剛剛結束了使用常規UIButton類的backgroundColor並使用它繪製一個圓。它現在更新正確。謝謝你的幫助!! – ultraflex

0

我複製你的代碼,並在我的演示中使用它。它的工作很好,當我改變「buttonColor」在IB.So它,當你在代碼中更改「buttonColor」看來,你必須重新繪製你的按鈕:

var buttonColor: UIColor?{ 
    didSet{ 
     setNeedsDisplay() 
    } 
}