In iOS apps sometimes we need to restrict our text field to take only numbers as an input, this can be done in several ways, let’s see some of them.
Method 1: Changing the Text Field Type from storyboard.
- Select the text field that you want to restrict to numeric input.
- Go to its attribute inspector.
- Select the keyboard type and choose number pad from there.
Method 2: Programmatically limiting inputs to number.
- Select the text field
- Create its outlet in the view controller.
- Conform the view controller to UITextFieldDelegate
- Set the text field’s delegate
- Add the following function
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
return true
} else {
return false
}
}
Our whole example class looks like
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tf: UITextField!
override func viewDidLoad() {
tf.delegate = self
super.viewDidLoad()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits) {
return true
} else {
return false
}
}
}
This will create a text field that can only take digits as input and no other character.