Suclassing UIButton of type .system

I'm trying to subclass UIButton, but I want it to be of type .system. I am struggling with initializers

class FormButton: UIButton {

var type FormButtonType: FormButtomType.oneSelection

init(oftype formType: FormButtomType) {
    self.type = formType
    super.init(type: .system)
}

} 

      

the problem is that I have the following error message: "Must call superclass designated initializer" UIButton "

+3


source to share


3 answers


You cannot override the convenience method and call the super convenience method ... Alternatively, you can make a static method that returns the FormButton

type UIButtonType.system

.

class FormButton: UIButton {
    class func newButton() -> FormButton {
        return FormButton.init(type: .system)
    }
}

      



Use it like this:

let button = FormButton.newButton()

      

+1


source


For the initializer of the assigned superclass call, you need to:



init(oftype formType: FormButtomType) {

    super.init(frame: yourframe)
    self.type = formType

}

      

0


source


The error is a little confusing

Should call the designated superclass initializer 'UIButton'

but what it is trying to say is that you need to call the designated initializer before using it self

. So the call self.type

causes the call super.init

. You've created an initializer convenience

that doesn't require calling super, you need to call self

.

First of all, this line is syntactically incorrect.

 var type FormButtonType: FormButtomType.oneSelection

      

should be

 var type: FormButtonType = FormButtomType.oneSelection

      

Now you can easily subclass it.

import UIKit

class FormButton: UIButton {

    var type: FormButtonType = FormButtomType.oneSelection

    // convenence initializer, simply call self if you have
    // initialized type
    convenience init(type: UIButtonType) {
        self.init(type: type)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

      

Now, if you want to initialize any property that has no default or is optional, you need a override

designated initializer.

For example,

class FormButton: UIButton {

    var type: UIButtonType = UIButtonType.system
    var hello: String // property doesn't have initial value

    // This is designated initialiser
    override init(frame: CGRect) {
        self.hello = "Hello"

        super.init(frame: .zero)
    }

    convenience init(type: UIButtonType) {
        self.init(type: .system)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

      

0


source







All Articles