0

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

  • Does this answer your question? [How to change UITextField keyboard type to email in Swift](https://stackoverflow.com/questions/26404373/how-to-change-uitextfield-keyboard-type-to-email-in-swift) – NicolasElPapu Apr 29 '20 at 12:28

2 Answers2

0

Tried setting your textField's keyboard type?

yourTextField.keyboardType = .numberPad

Can also look into the delegate method

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}

You can from there add logic to return true or false if the textField's selection meets your requirements

Waylan Sands
  • 321
  • 3
  • 11
0

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
        }

    }
iShox
  • 367
  • 2
  • 10