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!
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")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With