Search code examples
iosswiftuitextfielduitextfielddelegate

How to enable a clear button action in UITextField (swift)?


I'm pretty new to Swift and I have a problem that I don't know how to solve. So, I have a UITextField where I have a limit of 5 characters max in the text field and I have no problems with stopping on fifth character, but the problem is that I can't clear text, because clear button probably consider to be a character in iOS.

Anyone can help me to solve this problem?

Here is my code:

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

    if let count = textField.text?.characters.count {
        if count < 5 {
            print("\(count)")
            return true
        }
        else {
            return false
        }
    }
    return true
}

Thanks.


Solution

  • You need to check what the length of the text field would be, not what it currently is. Try this:

    func textField(textField: UITextField, 
              shouldChangeCharactersInRange range: NSRange, 
              replacementString string: String) -> Bool{
    
        let oldText: NSString = textField.text!
        let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)
    
        let count = newText.length 
        if count <= 5 {
             print("\(count)")
             return true
        } else {
             return false
        }
    }
    

    Note: I'm not fluent in Swift. There may be a syntax error or two in this code.