How to restrict UITextField to take only numbers in Swift?

后端 未结 30 937
难免孤独
难免孤独 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 08:53

    While most of these solutions will work, be aware that in some localisations a decimals are separated with a "," and not a "."

    The cleaner way to do this would be

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let decimalCharacter = NSNumberFormatter().decimalSeparator
        let characterSet = NSMutableCharacterSet.decimalDigitCharacterSet()
        characterSet.addCharactersInString(decimalCharacter)
    
        return replacementString.rangeOfCharacterFromSet(characterSet.invertedSet) == nil
    }
    

提交回复
热议问题