0

I am trying to subclass a UIButton so that its default initilizer sets it up the same way it would if you called UIButton(type: UIButtonType.roundedRect). However, I am unable to due to some Swift restrictions saying that that is not a designated initilizer. Additionally the buttonType property is read only.

How can I do this in Swift?

For reference this code does not compile because I do not call a designated initializer.

class ToggleButton : UIButton {
    init() {
        super.init(type: UIButtonType.roundedRect)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("TROUBLE")
    }
}
Khushbu
  • 2,342
  • 15
  • 18
J.Doe
  • 1,502
  • 13
  • 47
  • If you want to implement your custom init() methods, then compulsory you have to use designated initializer. – Khushbu May 21 '18 at 05:34
  • possible duplicate https://stackoverflow.com/questions/32343198/cannot-subclass-uibutton-must-call-a-designated-initializer-of-the-superclass – Dheeraj D May 21 '18 at 05:49

1 Answers1

4

Swift can be a little annoying with the initializers. This should do it for you.

class ToggleButton : UIButton {
    convenience init() {
        self.init(type: .roundedRect)
    }
    
    convenience init(type buttonType: UIButtonType) {
        self.init(type: buttonType)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("TROUBLE")
    }
}

EDIT: Feb 12, 21

As of Swift 5, this can be accomplished with the following.

class ToggleButton: UIButton {
    convenience init() {
        self.init(type: .roundedRect)
    }
}
cnotethegr8
  • 7,342
  • 8
  • 68
  • 104