Reputation: 4278
I'm new to Swift, coming from web dev, so I am quite used to components. I am trying to create a form, and would like to reuse the textfield and label in other Views. I have created a new class that inherence from UIView, and want to override the init to create set new properties.
My code so far
final class TextFormField: UIView {
var labelText: String
var secureText: Bool
var keyboardType: UIKeyboardType
override init(frame: CGRect) {
super.init(frame: frame)
}
init(labelText: String, secureText: Bool, keyboardType: UIKeyboardType){
self.labelText = labelText
self.secureText = secureText
self.keyboardType = keyboardType
super.init()
}
convenience init() {
self.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The error I get now is Must call a designated initializer of the superclass 'UIView'
on the second init.
How can I override the init to take 3 more parameters? Do I need to do an extension instead?
Thanks in advance
Upvotes: 1
Views: 93
Reputation: 28902
There are two issues in your code preventing it from compiling:
The override init(frame: CGRect)
does not initialize the variables you've declared (labelText
, secureText
, keyboardType
).
To resolve this, you have the following options:
add default values:
var labelText: String = ""
make the variables implicitly unwrapped - note that the variables may be nil when not initialized before usage
var labelText: String!
omit the override init(frame: CGRect)
method as you're not using it. That'll also allow you to keep your current variable declarations.
In init(labelText: String, secureText: Bool, keyboardType: UIKeyboardType)
, you need to call a super-initializer.
To do so, replace:
super.init()
with:
super.init(frame: .zero)
Upvotes: 2
Reputation: 54706
You should get rid of all unnecessary initialisers and make sure that your custom init
method calls one of the designated initialisers of super
.
final class TextFormField: UIView {
var labelText: String
var secureText: Bool
var keyboardType: UIKeyboardType
init(labelText: String, secureText: Bool, keyboardType: UIKeyboardType){
self.labelText = labelText
self.secureText = secureText
self.keyboardType = keyboardType
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Upvotes: 2