Custom class that inherits from UITextField does not work (with custom init) in Swift

8.4k views Asked by At

So the title says it all. I am trying to create a class that explicitly inherits from UITextField. This is because I want to do some customization to my UITextFields. My main goal though, is to create a custom initializer for the class, however, I run into trouble by doing so.

Here is my code:

import UIKit

class CustomTextField: UITextField {

    //Class variables

    required init(coder decoder: NSCoder, other:String) {
        super.init(coder: decoder)
        self.layer.cornerRadius = 15
        println("Instantiated")
        println(other)

    }
}

But the compiler complains with: 'required' initializer 'init(coder:)' must be provided by subclass of 'UITextField'. Then I go ahead and apply the suggested fix for the problem, and it adds the following code right below my required init code:

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

My code above never prints "Instantiated"

Could you please help me out? My ideal class would receive at least another 2 arguments in the initializer (besides the coder-NSCoder one). I don't get why I can't get this to work (maybe I am too used to Java, where doing this is easier).

Thank you so much for your help in advance!

Cheers!

2

There are 2 answers

7
Eendje On BEST ANSWER

If you want to do it programmatically:

class CustomTextField: UITextField {

    init(frame: CGRect, arg1: CGFloat, arg2: String) {
        super.init(frame: frame)

        self.layer.cornerRadius = arg1
        print(arg2)
        print("Instantiated")
    }

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

required init(coder) is mandatory even if you don't use it.

If your text field is added in storyboard, don't forget to change the class of that field to CustomTextField in Identity Inspector and you can use the code below to customize some things:

class CustomTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()

        layer.cornerRadius = 5
        layer.borderColor = UIColor.greenColor().CGColor
        layer.borderWidth = 1.0

        // Set other stuff like font color etc.

        print("Instantiated")
    }
}
5
Icaro On

If you are just using the storyboard you won't need custom or convenience initializers, just override the super initializer and start your variables before call supper, as in the code below.

import UIKit

class MyTextView: UITextView {

    var myValue:Int
    var myText:String


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

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        myText = String()
        myValue = Int()
        super.init(frame: frame, textContainer: textContainer)
    }

}