Laap
Laap

Reputation: 71

Custom UITextField, init with no arguments

I have a custom UITextField and I'm trying to declare it like:

let textField = StandardTextField() // pretty much like UITextField()

My custom text field looks like:

class StandardTextField: UITextField {

    init(frame: CGRect, size: CGFloat) {
        super.init(frame: frame)

        // some initialization
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

This is giving me an error because TextField has no initializer with no arguments. I tried adding:

init() {
    super.init()
}

But this isn't possible since super.init() isn't the designated initializer. How can I achieve this?

Upvotes: 2

Views: 2304

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236558

You are probably looking for a convenience initialiser. But you will need to define a default frame size for your UITextField. Try like this:

class StandardTextField: UITextField {
    convenience init() {
        self.init(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
        // some initialisation for init with no arguments
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        //  some initialisation for init with frame
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Upvotes: 4

pbush25
pbush25

Reputation: 5248

Well unless I'm blatantly missing something, you've declared your class as class Textfield: UITextField and based on how you're trying to create your object, your class should be defined as class StandardField: UITextField and the class doesn't need any initializers as Leo said.

class StandardTextField: UITextField {
    //no initializers
}

Upvotes: 0

Related Questions