How to restrict UITextField to take only numbers in Swift? How to restrict UITextField to take only numbers in Swift? swift swift

How to restrict UITextField to take only numbers in Swift?


Solution for swift 3.0 and above

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)}


Here is my 2 Cents. (Tested on Swift 2 Only)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {  let aSet = NSCharacterSet(charactersInString:"0123456789").invertedSet  let compSepByCharInSet = string.componentsSeparatedByCharactersInSet(aSet)  let numberFiltered = compSepByCharInSet.joinWithSeparator("")  return string == numberFiltered}

This is just a little bit more strict. No decimal point either.

Hope it helps :)

PS: I assumed you looked after the delegate anyway.

Update: Swift 3.0 :

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {    let aSet = NSCharacterSet(charactersIn:"0123456789").inverted    let compSepByCharInSet = string.components(separatedBy: aSet)    let numberFiltered = compSepByCharInSet.joined(separator: "")    return string == numberFiltered}


In swift 4.1 and Xcode 9.4.1

Add UITextFieldDelegate to your class

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your viewDidLoad()

mobileNoTF.delegate = self

Write this textfield delegate function

//MARK - UITextField Delegatesfunc textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {    //For mobile numer validation    if textField == mobileNoTF {        let allowedCharacters = CharacterSet(charactersIn:"+0123456789 ")//Here change this characters based on your requirement        let characterSet = CharacterSet(charactersIn: string)        return allowedCharacters.isSuperset(of: characterSet)    }    return true}