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.
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()
}
}
}