Skip to content

Instantly share code, notes, and snippets.

View kuratowsky's full-sized avatar

Benet Joan Darder Canyelles kuratowsky

View GitHub Profile
@kuratowsky
kuratowsky / gist:6e027fd2270d5bf5ac4ee41764e4bfdb
Last active June 4, 2023 09:51 — forked from shekarsiri/gist:2822b0958e967860ed07d2d63529ffeb
UITextField accept only numbers to certain limits (Swift 5 Tested.)
// let MAX_LENGTH_PHONENUMBER = 15
// let ACCEPTABLE_NUMBERS = "0123456789"
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength: Int = textField.text!.count + string.count - range.length
let numberOnly = NSCharacterSet.init(charactersIn: ACCEPTABLE_NUMBERS).inverted
let strValid = string.rangeOfCharacter(from: numberOnly) == nil
return (strValid && (newLength <= MAX_LENGTH_PHONENUMBER))