Ask Your Question
3

How to limit UITextField input to only accept numerical values?

asked 2022-11-24 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-18 11:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-24 11:00:00 +0000

Seen: 21 times

Last updated: May 18 '22