Search code examples
swift2uitextfieldlimit

How do I limit UITextField length AND character types at the same time?


I have an iOS Xcode 7.3 project I working on using Swift2. I've looked all over and found ways to limit the length of text in a UITextField. I've also seen ways to limit the types of characters that an be typed in a UITextField.

I've used in my project for length limit:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    let limitLength = 3
    return newLength <= limitLength
}

I've used this for limiting the text to only numeric values:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
    let stringFromTextField = NSCharacterSet.init(charactersInString: string)
    let strValid = numberOnly.isSupersetOfSet(stringFromTextField)

    return strValid
}

Both work great once I set my UITextField to the UITextFieldDelegate. However, I need my project to do both. How do I do that? How can I combine the two since they each have a different return type and value?

The issue is when I use the iPad, it allows for other characters besides numeric because the .NumberPad for the iPad allows for characters such as &,$,%, etc. The iPhone has no issues, but my project is a universal app.


Solution

  • Simply only return from the first type of check if the condition is false, otherwise continue to the second check:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return true }
        let newLength = text.characters.count + string.characters.count - range.length
        let limitLength = 3
        if newLength > limitLength {
            return false
        }
    
        let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
        let stringFromTextField = NSCharacterSet.init(charactersInString: string)
        let strValid = numberOnly.isSupersetOfSet(stringFromTextField)
    
        return strValid
    }