I am making an iPad-app to learn english words. It needs to check the input in a textfield as soon as the characters are typed in the textfield. I am using the swift function shouldChangeCharactersInRange to accomplish this.
My code:
func textField(textField: UITextField, shouldChangeCharactersInRange range:NSRange, replacementString string: String) -> Bool {
if TextField1.text == "apple" {
checkImageView1.hidden = false
}
else {
checkImageView1.hidden = true
}
return true
}
It needs to show an image if the word is typed right, in this case "apple". The problem is that when te user types in the "e" of "apple" the check only sees "appl" and therefor doesn't show the image.
Anyone know how to solve this?
You could use a target on your textField
with the control event EditingChanged
instead of the delegate method.
Swift >= 1.0
myTextField.addTarget(self, action: "didChangeText:", forControlEvents: .EditingChanged)
Swift 3.0 (String literal selectors are deprecated, use #selector)
myTextField.addTarget(self, action: #selector(didChangeText(_:)), for: .editingChanged)
Then use the targeted method to run your checks.
func didChangeText(textField:UITextField) {
if textField.text == "apple" {
checkImageView1.hidden = false
} else {
checkImageView1.hidden = true
}
}
While Wezly's answer is correct, the reason why it's only seeing "appl" instead of "apple" is because the text of the textField
isn't updated with the latest entry at that point, as the name of the delegate method states shouldChangeCharactersInRange
. Instead of checking the text of the textField
, you should do the replacement of the new entry and check the new value with something like below:
Swift 3
let newText = textField.text?.replacingCharacters(in: range, with: string)
Using the event EditingChanged
would work if you just want to get the latest value, but if you want to do some validation of each entry before the text is actually edited, you have to go with the delegate method.
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