I want all of TextField to have small letters.and if I need to change to a larger one I could write inside the creation.But my code doesn’t work, what am I doing wrong?
class ViewController: UIViewController
private let TextField: CustomTextField = { //LETTERS (no work)
let textfield = CustomTextField()
textfield.autocapitalizationType = .allCharacters
return textfield
}()
private let TextField2: CustomTextField = { //letters (work)
let textfield = CustomTextField()
return textfield
}()
class CustomTextField: UITextField
override func layoutSubviews() {
super.layoutSubviews()
self.autocapitalizationType = .none
}
2
Answers
layoutSubviews()
function is called after the initialization of your textFields. If you debug your code, you will see thatTextField.autocapitalizationType
will be set to.allCharacters
. But after initialization of your object,layoutSubviews()
will be called andautocapitalizationType
will be set to.none
. So you need to define theself.autocapitalizationType = .none
insideinit
of yourCustomTextField
.First, remove the override of
layoutSubviews()
– as mentioned by Muhammed’s answer, setting theautocapitalizationType
here will overwrite your custom value as soon aslayoutSubviews()
is called.Then, if you give your
CustomTextField
a custom initializer with a parameter for the capitalization type like this:Then you can just initialize it all in one step like this, no closure required:
If you don’t want to set a type then you can leave the
CustomTextField()
parentheses empty since the initializer adds.none
as a default.