SteveSmith SteveSmith - 2 years ago 82
Swift Question

How to prevent specific characters from being typed in textfield?

I would like to know how I could prevent certain characters from being allowed to be typed in a UITextfield. For example If I do not want the letters A,G,P,Q,X from being typed inside this textfield but the rest of the letters are allowed.

I am very new to this and thank you for the help!

Answer Source

You need to use UITextViewDelegate for that. Catch user's input in one of the delegate methods, and handle it as you wish.

Here is the Apple Reference for it:


You might need to use this function.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    inputString = inputString.stringByReplacingCharactersInRange(range, withString: string)

It really depends on how you want to handle "not allowing" specific chars.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download