问题
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