0
\$\begingroup\$

The goal is to disallow typing alphabetic characters as input in a UITextField.

Please tell me if this approach is convenient.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let charSet = CharacterSet.letters
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSeparator = string.range(of: ".")
        let existingTextHasAlphabeticCharacters = textField.text?.rangeOfCharacter(from: charSet)
        let replacementTextHasAlphabeticCharacters = string.rangeOfCharacter(from: charSet)

        if existingTextHasDecimalSeparator != nil,
            replacementTextHasDecimalSeparator != nil {
            return false
        } else if existingTextHasAlphabeticCharacters != nil ||
                    replacementTextHasAlphabeticCharacters != nil {
                return false
        } else {
            return true
        }
    }
\$\endgroup\$
2
\$\begingroup\$

If you want to disallow letters as input, why do you also test the old string of the text field? And why do you test, if the old and the new string contain a dot? The very simple solution to forbid letters is to use the one liner

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet.letters) == nil
}

or

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")) == nil
}

if you want to be more specific about the disallowed characters.

\$\endgroup\$
  • \$\begingroup\$ Hello, sorry I forgot to delete the dot check statement. \$\endgroup\$ – ttppbb Feb 23 '18 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.