Santis
Santis

Reputation: 115

Limit UITextField input to numbers in Swift

How can I get limit the user's TextField input to numbers in Swift?

Upvotes: 8

Views: 26252

Answers (5)

Akbar Khan
Akbar Khan

Reputation: 2415

1st you have to inherit the UITextViewDelegate class with you own class

class ViewController: UIViewController, UITextViewDelegate {

2nd add an IBOutlet

@IBOutlet weak var firstName: UITextField!

3rd you have to assure this object is using

override func viewDidLoad() {
        super.viewDidLoad()
   firstName.delegate = self
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == firstName {
                let allowedCharacters = "1234567890"
                let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                let typedCharacterSet = CharacterSet(charactersIn: string)
                let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                let Range = range.length + range.location > (fnameTF.text?.count)!

        if Range == false && alphabet == false {
            return false
        }


        let NewLength = (fnameTF.text?.count)! + string.count - range.length
        return NewLength <= 10


      } else {
        return false
    }
  }

Upvotes: 1

Patrick Lin
Patrick Lin

Reputation: 166

For anyone looking for a shorter answer, I've found this quite useful.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // remove non-numerics and compare with original string
    return string == string.filter("0123456789".contains)
}

Works in XCode 10.1, Swift 4.2

Upvotes: 7

Naresh
Naresh

Reputation: 17932

In swift 4.1 and Xcode 10

Add UITextFieldDelegate to your class

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your viewDidLoad()

yourTF.delegate = self

Write this textfield delegate function

//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //For numers
    if textField == yourTF {
        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
}

Upvotes: 1

Lyndsey Scott
Lyndsey Scott

Reputation: 37300

You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool {

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.componentsSeparatedByCharactersInSet(inverseSet)

    // Rejoin these components
    let filtered = components.joinWithSeparator("")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered
}

Updated for Swift 3:

 func textField(_ textField: UITextField, 
    shouldChangeCharactersIn range: NSRange, 
    replacementString string: String) -> Bool {

    // Create an `NSCharacterSet` set which includes everything *but* the digits
    let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

    // At every character in this "inverseSet" contained in the string,
    // split the string up into components which exclude the characters
    // in this inverse set
    let components = string.components(separatedBy: inverseSet)

    // Rejoin these components
    let filtered = components.joined(separator: "")  // use join("", components) if you are using Swift 1.2

    // If the original string is equal to the filtered string, i.e. if no
    // inverse characters were present to be eliminated, the input is valid
    // and the statement returns true; else it returns false
    return string == filtered  
}

Upvotes: 43

ldindu
ldindu

Reputation: 4380

Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,

(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

You need to implement the following method and intercept the entered character and either through the following regular expression

"^([0-9]+)?(\\.([0-9]{1,2})?)?$"

or

[NSCharacterSet decimalDigitCharacterSet]

you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.

Upvotes: 0

Related Questions