2016-03-29 78 views
6

我想繼承UIButton,並添加一個屬性isActive,這是一個Bool,它改變了按鈕的外觀(這與默認的.enabled屬性無關)。如何用Swift中的按鈕類型覆蓋UIButton的init?

但是,我也想在初始化時設置按鈕類型。具體而言,我想多初始化它喜歡它是UIButton,如:

let button = MyButton(type: .Custom) 

但是,由於.buttonType是隻讀的,我不能只是覆蓋它想:

convenience init(type buttonType: UIButtonType) { 
    buttonType = buttonType 
    self.init() 
} 

這吐奶出錯:Cannot assign to value: 'buttonType' is a 'let' constant(我已經執行了所需的init(coder:))。

那麼初始化時如何設置.buttonType


注:自定義屬性應同樣適用於其他函數內改變它的邏輯,所以我拿起一個屬性,而不是定義兩個函數來改變它的外表。

+0

'按鈕類型= buttonType'確實在迅速是否有意義? – Fonix

+0

嘗試'self.buttonType = buttonType' – Chris

+0

@Chris它得到了同樣的結果。 – Blaszard

回答

-8

按鈕類型是隻讀的,所以你必須設置通過的UIButton的便利初始化類型:

convenience init(type buttonType: UIButtonType) { 
    self.init(type: buttonType) 
    // assign your custom property 
} 
+0

沒有。無盡的循環。 –