Limit UITextField input to numbers in Swift

后端 未结 6 1115
南旧
南旧 2020-12-05 12:10

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

相关标签:
6条回答
  • 2020-12-05 12:44

    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
        }
      }
    
    0 讨论(0)
  • 2020-12-05 12:52

    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
    }
    
    0 讨论(0)
  • 2020-12-05 12:54

    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  
    }
    
    0 讨论(0)
  • 2020-12-05 12:54

    Here is the simple solution which could help out on iPhone.

    Change Keyboard type to number

    You can simply change keyboard type property of textfield to number pad here is the screen shot of the property to change

    Screen shot

    0 讨论(0)
  • 2020-12-05 12:57

    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

    0 讨论(0)
  • 2020-12-05 12:58

    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.

    0 讨论(0)
提交回复
热议问题