chickenparm chickenparm - 6 months ago 55
Swift Question

Limiting characters and character length in textField(_:shouldChangeCharactersInRange:replacementString:)

I have a username textField in my app that I want to limit to 24 characters and not allow "|" a pipe in the username.

I am able to do each of these individually with the code below but I have having trouble combining these both into textField(_:shouldChangeCharactersInRange:replacementString:).

This code is successfully disallows a "|" in the username field.

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

if textField === usernameField {
// Create an `NSCharacterSet` set
let set = NSCharacterSet(charactersInString:"|")

// At every character in this "set" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(set)

// Rejoin these components
let filtered = components.joinWithSeparator("")

// If the original string is equal to the filtered string, i.e. if no
// characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
} else {
return true
}
}


This code successfully limits the username field to 24 characters.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Added to limit title to <= 40 characters
guard let text = meetupTitleTextField.text else { return true }

let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 48 // Bool
}


I would really appreciate any advice on how to combine these both into textField(_:shouldChangeCharactersInRange:replacementString:)

Answer

Try this:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == usernameField, let text = textField.text {
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= 48 && !string.containsString("|")
    }

    return true
}