How to override UIButton init with button type in Swift?

I want to subclass UIButton and add to it the property isActive , which is Bool , which changes the appearance of the button (this does not apply to the .enabled property by default).

However, I also want to set the button type during initialization. In particular, I want to initialize it the same way as in UIButton , for example:

 let button = MyButton(type: .Custom) 

However, since .buttonType is read-only, I cannot just override it like this:

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

This spits out an error: Cannot assign to value: 'buttonType' is a 'let' constant (I already performed the required init(coder:) ).

So how can I set .buttonType on initialization?


NOTE. A custom property should also be used in other functions to change the logic inside it, so I took the property instead of defining two functions to change the appearance.

+6
source share
1 answer

buttonType is read-only, so you need to set this type using the UIButton convenience initializer:

 convenience init(type buttonType: UIButtonType) { self.init(type: buttonType) // assign your custom property } 
-eight
source

All Articles