title: Swift checking textfield input live
body: <p>I've been struggling to find how to check the input of a textfield as a user is typing.</p>
  
  <p>if a user types a word, it should change a label and an image according to some defined rules.</p>
  
  <p>my code is working, but I'm always a step behind. (as it reads the content always before the next character is entered. </p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -&gt; 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) -&gt; Bool {
          println("validate password: \(testStr2)")
          
          let passwordRegEx = "[A-Z0-9a-z._%+-:/&gt;&lt;#]{6,30}"
          
          if let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegEx) {
              return passwordTest.evaluateWithObject(testStr2)
          }
          
          return false       </code></pre>
  </div>
  </div>
  </p>