You can use the keyboardType
property of a UITextField
to restrict input to only numeric values.
Here's an example:
main.swift80 chars3 lines
In the example above, .numberPad
specifies that the keyboard will only show numbers and decimal point. You can also use .decimalPad
if you want to allow decimal points in addition to numbers.
However, this does not prevent users from pasting non-numeric symbols into the field. To ensure only numbers are entered, you can use text field delegate method like below:
main.swift303 chars6 lines
This method should be implemented in the text field's delegate, and it will only allow numeric characters to be entered into the text field.
gistlibby LogSnag