Reputation: 19572
I have a textField that I disable capital letters by setting .autocapitalizationType = .none
and in shouldChangeCharactersIn range
I replace any capital letters with lowercased letters
by using this answer.
Forcing only lowercase letters works fine but the target method I added to .editingChanged
stopped working.
Why did .editingChanged
stop working?
let emailTextField: UITextField = {
let textField = UITextField()
return textField
}()
let userNameTextField: UITextField = {
let textField = UITextField()
textField.autocapitalizationType = .none
textField.addTarget(self, action: #selector(printSomething), for: .editingChanged)
return textField
}()
@objc func printSomething() {
// as I type inside the usernameTextField this no longer prints
print("something")
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// only change characters for username textfield
if textField == userNameTextField {
userNameTextField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased())
return false
}
return true
}
Upvotes: 0
Views: 809
Reputation: 236295
The problem is your userNameTextField declaration. When you initialise it there is no self
. You need to change its declaration to lazy
:
lazy var userNameTextField: UITextField = {
let textField = UITextField()
textField.autocapitalizationType = .none
textField.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
return textField
}()
I would also remove the shouldChangeCharacters in range and do all your character manipulation inside editingChanged method:
@objc func editingChanged(_ textField: UITextField) {
print(textField.text!)
textField.text = textField.text!.lowercased()
}
Upvotes: 0
Reputation: 624
Change to return true
if textField == userNameTextField {
userNameTextField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased())
return true
}
Upvotes: 1