xxxxxxxxxx
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// you can set the following two properties for the text field in Interface Builder, if you'd prefer
textField.delegate = self
textField.keyboardType = .numberPad
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters) == nil
}
// or, alternatively:
//
// func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// return string.range(of: "^\\d*$", options: .regularExpression) != nil
// }
}
xxxxxxxxxx
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let bytes: [Unicode.UTF8.CodeUnit] = Array([0x7F, 0x08, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2E, 0x2D])
let newString = String(bytes: bytes, encoding: String.Encoding.utf8)!
if let x = string.rangeOfCharacter(from: NSCharacterSet.init(charactersIn: newString) /* decimalDigits */ /* init(charactersIn: stringa) */ as CharacterSet) {
return true
} else {
return false
}
}