\$\begingroup\$
\$\endgroup\$
1
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
-
\$\begingroup\$ Please see What to do when someone answers . I have rolled back Rev 5 → 4. \$\endgroup\$200_success– 200_success2018年02月23日 00:29:09 +00:00Commented Feb 23, 2018 at 0:29
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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.
-
\$\begingroup\$ Hello, sorry I forgot to delete the dot check statement. \$\endgroup\$ttppbb– ttppbb2018年02月23日 00:33:36 +00:00Commented Feb 23, 2018 at 0:33
default