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
 }
 }
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 13, 2018 at 6:07
\$\endgroup\$
1

1 Answer 1

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.

answered Feb 21, 2018 at 21:23
\$\endgroup\$
1
  • \$\begingroup\$ Hello, sorry I forgot to delete the dot check statement. \$\endgroup\$ Commented Feb 23, 2018 at 0:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.