4

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!

dan
  • 9,695
  • 1
  • 42
  • 40
SteveSmith
  • 269
  • 2
  • 12

2 Answers2

3

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:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/#//apple_ref/occ/intfm/UITextViewDelegate/textView:shouldChangeTextInRange:replacementText:

EDIT:

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.

Eugene Gordin
  • 4,047
  • 3
  • 47
  • 80
  • Thank you for the guidance. If it's not to much to ask would you be able to provide some sample code? I am very very new to Swift. Thank you so much. – SteveSmith May 02 '16 at 19:54
  • check my edits...also this link might be helpful: http://stackoverflow.com/a/31502884/1585677 – Eugene Gordin May 02 '16 at 19:56
  • Thanks for the help! – SteveSmith May 02 '16 at 19:59
  • 1
    You can check for the specific characters in that delegate method or you can actually check the ascii value of the character being input. If your app is used for multiple regions you might want to check the ascii value of each character so you dont have to type in each specific character for each language – Esko918 May 02 '16 at 19:59
1

I would deal this type of issue with ASCII code. Make sure your textField delegate protocol(UITextFieldDelegate) included and textField delegate assigned to self.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        var singleChar = string

        let code = singleChar.unicodeScalars.first?.value

        print(code)

        if(code == 65 || code == 71 || code == 80 || code == 81 || code == 88 )
        {

        return false;
        }

        return true;

    }
Shashi3456643
  • 2,021
  • 17
  • 21
  • This method does not work if the user pastes a chunk of text, since it'll be more than a single char, which is improperly being assumed. – Jake T. Jun 02 '17 at 18:48