Edwin Wiersma Edwin Wiersma - 1 year ago 108
Swift Question

Textfield shouldchangecharactersinrange swift

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?

Answer Source

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(_:)), forControlEvents: .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