create a textfield which only take number in it in swift

You can use the keyboardType property of a UITextField to restrict input to only numeric values.

Here's an example:

main.swift
let numericTextField = UITextField()
numericTextField.keyboardType = .numberPad
80 chars
3 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.swift
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacterSet = CharacterSet.decimalDigits
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacterSet.isSuperset(of: characterSet)
}
303 chars
6 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