Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift checking textfield input live

I've been struggling to find how to check the input of a textfield as a user is typing.

if a user types a word, it should change a label and an image according to some defined rules.

my code is working, but I'm always a step behind. (as it reads the content always before the next character is entered.

If it just to check the length I could use countElements(textfield) + 1, but I want it to also show that a user cannot use certain characters as they are typing, therefore that would not work for checking undesired characters.

I am assuming the function I am using is not the right one "shouldChangeCharacters". So I am a bit lost as to what to use. Is there a way to read a println or NSLog command to return to an outlet?

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let passwordcheck = UserPasswordTextField.text

       
        if UserPasswordTextField.isFirstResponder() {
            if isValidPassword(passwordcheck) {
            PWimg.image = UIImage(named: "passwordapprovedicon")
            } else if passwordcheck.isEmpty {
                PWimg.image = UIImage(named: "passwordiconwrong")
            } else {
            PWimg.image = UIImage(named: "passwordiconwrong")
            }
}

     func isValidPassword(testStr2:String) -> Bool {
        println("validate password: \(testStr2)")
        
        let passwordRegEx = "[A-Z0-9a-z._%+-:/><#]{6,30}"
        
        if let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegEx) {
            return passwordTest.evaluateWithObject(testStr2)
        }
        
        return false       
like image 290
William Larson Avatar asked Dec 19 '22 05:12

William Larson


2 Answers

Listen for UIControlEventEditingChanged events from the text field. Register for them either with

  1. the Interface Builder: drag from the text field to the file, and select the action type "Editing Changed"

  2. the following code:

    override func viewDidLoad() {
        super.viewDidLoad()
        // ... 
        textField.addTarget(self, action:"edited", forControlEvents:UIControlEvents.EditingChanged)
    }
    
    func edited() {
       println("Edited \(textField.text)")
    }
    
like image 112
Teemu Kurppa Avatar answered Dec 24 '22 03:12

Teemu Kurppa


Updated for swift 3:

 override func viewDidLoad() {
     super.viewDidLoad()
     //...
     textField.addTarget(self, action: #selector(textFieldDidChange), for:.editingChanged)
 }

 func textFieldDidChange(){
     print(textField.text)
 }
like image 39
Eli Byers Avatar answered Dec 24 '22 01:12

Eli Byers