How to prevent specific characters from being typed in textfield?

这一生的挚爱 提交于 2019-12-10 23:06:44

问题


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!


回答1:


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.




回答2:


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;

    }


来源:https://stackoverflow.com/questions/36990541/how-to-prevent-specific-characters-from-being-typed-in-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!