How to restrict UITextField to take only numbers in Swift?

后端 未结 30 881
难免孤独
难免孤独 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: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

提交回复
热议问题