How to restrict UITextField to take only numbers in Swift?

后端 未结 30 800
难免孤独
难免孤独 2020-12-04 08:40

I want the user to only enter numeric values in a UITextField. On iPhone we can show the numeric keyboard, but on iPad the user can switch to any keyboard.

相关标签:
30条回答
  • 2020-12-04 09:15

    Here is a simple solution, you need to connect the event "Editing changed" to this method in your controller

    Swift 4

    @IBAction func valueChanged(_ sender: UITextField) {
        if let last = sender.text?.last {
            let zero: Character = "0"
            let num: Int = Int(UnicodeScalar(String(last))!.value - UnicodeScalar(String(zero))!.value)
            if (num < 0 || num > 9) {
                //remove the last character as it is invalid
                sender.text?.removeLast()
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 09:15

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

    class ViewController: UIViewController, UITextFieldDelegate {
    

    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)
                    return alphabet
    
    
          }
      }
    
    0 讨论(0)
  • 2020-12-04 09:16

    Swift 2.0

    For only allowing numbers and one "." decimal in uitextfield.

    func textField(textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
    {
        let newCharacters = NSCharacterSet(charactersInString: string)
        let boolIsNumber = NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(newCharacters)
        if boolIsNumber == true {
            return true
        } else {
            if string == "." {
                let countdots = textField.text!.componentsSeparatedByString(".").count - 1
                if countdots == 0 {
                    return true
                } else {
                    if countdots > 0 && string == "." {
                        return false
                    } else {
                        return true
                    }
                }
            } else {
                return false
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 09:17
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    
            {
                let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    
                if textField == self.phoneTextField  && string.characters.count > 0{
                    let numberOnly = NSCharacterSet.decimalDigits
                    let strValid = numberOnly.contains(UnicodeScalar.init(string)!)
                    return strValid && textString.characters.count <= 10
                }
                return true
            }
    

    in above code is working in swift 3
    NSCharacterSet.decimalDigits
    You are also use letters only
    NSCharacterSet.Letters
    and uppercase,Lowercaseand,alphanumerics,whitespaces is used same code or See the Link

    0 讨论(0)
  • 2020-12-04 09:17

    Dead simple solution for Double numbers (keep it mind that this is not the best user-friendly solution), in your UITextFieldDelegate delegate:

    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
            guard let currentString = textField.text as NSString? else {
                return false
            }
            let newString = currentString.replacingCharacters(in: range, with: string)
            return Double(newString) != nil
    }
    
    0 讨论(0)
  • 2020-12-04 09:19

    To allow only numbers and just one decimal operator, you can use this solution:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let isNumber = NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(NSCharacterSet(charactersInString: string))
    
        return isNumber || (string == NSNumberFormatter().decimalSeparator && textField.text?.containsString(string) == false)
    }
    
    0 讨论(0)
提交回复
热议问题