8

I want to subclass UIButton and add to it a property isActive, which is a Bool that changes the look of the button (this is not related to the default .enabled property).

However, I also want to set the button type when initialized. Specifically, I want to initialize it much like it is in UIButton, like:

let button = MyButton(type: .Custom)

However, because the .buttonType is a read-only, I cannot just override it like:

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 implemented the required init(coder:)).

So how can I set the .buttonType when initialized?


NOTE: The custom property shall be also used in other functions to change the logic within it, so I picked up a property, instead of defining two functions to change the look.

Blaszard
  • 30,954
  • 51
  • 153
  • 233
  • `buttonType = buttonType` does that make sense in swift? – Fonix Mar 29 '16 at 05:37
  • Try `self.buttonType = buttonType` – Chris Mar 29 '16 at 05:47
  • @Chris It got the same result. – Blaszard Mar 29 '16 at 05:50
  • @Blaszard Different button types are represented by different (private) subclasses of UIButton. That's why you can only set type at creation time but not after. What exactly do you want to do? Can you explain it to us thoroughly? I am smelling [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here. – Ozgur Vatansever Mar 29 '16 at 05:56
  • 1
    @ozgur I want to subclass `UIButton` and initialize it using `init(type:)` initializer. – Blaszard Mar 29 '16 at 06:01
  • Maybe this might help: http://stackoverflow.com/questions/13202161/why-shouldnt-i-subclass-a-uibutton – Ozgur Vatansever Mar 29 '16 at 06:13

2 Answers2

0

You don't need use it, according to documentation:

This method is a convenience constructor for creating button objects with specific configurations. If you subclass UIButton, this method does not return an instance of your subclass. If you want to create an instance of a specific subclass, you must alloc/init the button directly.

When creating a custom button—that is a button with the type UIButton.ButtonType.custom—the frame of the button is set to (0, 0, 0, 0) initially. Before adding the button to your interface, you should update the frame to a more appropriate value.

means button you created already custom, just use init()

Grigorii
  • 43
  • 6
-10

buttonType is read-only, so you have to set the type via UIButton's convenience initializer:

convenience init(type buttonType: UIButtonType) {
    self.init(type: buttonType)
    // assign your custom property
}
Chris
  • 489
  • 5
  • 15