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.
You can use shouldChangeCharactersInRange along with String extension method to check if the input string is number or not.
extension String {
var isNumber : Bool {
get{
return !self.isEmpty && self.stringWithoutWhitespaces.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
var stringWithoutWhitespaces: String {
return self.replacingOccurrences(of: " ", with: "")
}
}
//Mark: shouldChangeCharactersInRange
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// return true if the string only contains numeric characters
let isValid = string.stringWithoutWhitespaces.isNumber
return valid
}