在 UITextView 中防止小写 [英] Prevent lower case in UITextView
问题描述
我试图阻止用户在 UITextView 中输入任何小写字符.
I am trying to prevent the user from entering any lowercase characters into a UITextView.
我创建了一个可接受字符的#define 字符集
I have created a #define character set of acceptable characters
#define VALID_CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWYXZ1234567890"
现在我想知道当用户尝试输入与我的 VALID_CHARACTERS 不匹配的字符时,如何使用它在 UITextView 委托中返回 no.
Now I would like to know how to use this to return no in the UITextView delegate when the user tries to enter a character that dose not match my VALID_CHARACTERS.
推荐答案
我建议使用 textView:shouldChangeTextInRange:replacementText:
如果替换文本包含无效字符,则返回 NO.
I suggest using textView:shouldChangeTextInRange:replacementText:
and returning NO if the replacement text contains invalid characters.
编辑(回复您的评论):
Edit (in response to your comment):
// Goal: Remove all the non-valid characters from the replacement string
// then see if the string is the same as the original replacement string;
// if it is, then the string is valid and return YES, else return NO
- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// First step - define a character set with the valid characters
NSMutableCharacterSet *validSet = [NSMutableCharacterSet characterSetWithCharactersInString:VALID_CHARACTERS];
// Second step - define a character set with the inverse, i.e invalid characters
NSCharacterSet *invalidSet = [validSet invertedSet];
// Then remove all invalid characters by separating the string into components
// separated by the invalid characters using componentsSeparatedByCharactersInSet:
// and then rejoining the set using componentsJoinedByString: so that it now only
// contains valid characters
NSString *filteredString = [[string componentsSeparatedByCharactersInSet:invalidSet] componentsJoinedByString:@""];
// Compare that filtered string with the original string then see if its
// the same as the replacement string; if the same (i.e. no invalid characters
// have been removed), return yes, if not, return no.
return ([filteredString isEqualToString:string]);
}
这篇关于在 UITextView 中防止小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!