Search code examples
swiftintuitextfield

Swift - How to limit the a few specific text field only allow to insert int?


How to limit the few specific text field only allow to insert int? not all text fields. only a few specific ones. Thank you.


Solution

  • Try this one.

    class ViewController: UIViewController,UITextFieldDelegate {
    
            @IBOutlet var yourTextField: UITextField!
    
            override func viewDidLoad() {
                super.viewDidLoad()
                // Do any additional setup after loading the view.
                yourTextField.delegate = self
            }
    
            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                //For mobile numer validation
                if textField == yourTextField {
                    //Add specific int numbers
                    let allowedCharacters = CharacterSet(charactersIn:"0123 ")//Here change this characters based on your requirement
                    let characterSet = CharacterSet(charactersIn: string)
                    return allowedCharacters.isSuperset(of: characterSet)
                }
                return true
            }
    
        }