Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textfield shouldchangecharactersinrange swift

Tags:

ios

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?

like image 410
Edwin Wiersma Avatar asked Apr 13 '15 10:04

Edwin Wiersma


2 Answers

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
    }
}
like image 112
Wez Avatar answered Oct 13 '22 00:10

Wez


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.

like image 43
halil_g Avatar answered Oct 12 '22 23:10

halil_g