1 | initial version |
One way to limit UITextField input to only accept numerical values is by implementing the UITextFieldDelegate method shouldChangeCharactersIn range:
. Here's an example implementation in Swift:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
In this implementation, we define allowedCharacters
as the set of decimal digits. Then, we check if the characterSet
composed of the characters in string
is a subset of allowedCharacters
. If it is, we allow the change to occur, otherwise we block it.
Next, set the delegate
property of your UITextField instance to the view controller that implements the above delegate method. Now, the UITextField will only allow numerical input.