It’s easy for iPhone. Need only set it on your Storyboard:


But it doesn’t work for iPad. So, time for coding. Below is a solution to this problem for Swift 4.x-5.0 which I use in my application.

First of all, add UITextFieldDelegate here:

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var yourTextField: UITextField!

Delegate TextField:

override func viewDidLoad() {
  yourTextField.delegate = self

And finally implement it:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
  yourTextField.text = ""
  return false
Categories: App development