简体   繁体   中英

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!

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.

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;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM