问题
I am building an app for release in Taiwan so it will be mostly in Chinese however the usernames must be English. I'm not sure how to stop Chinese characters from being input. So far I have restricted the length of the username to 12 characters and the characters must be in the set defined below:
#define ACCEPTABLE_CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
I implemented the - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method and now my UITextField works for the two conditions above. However, although a Chinese character is not in the set it still appears due to pinyin being used to type it is english. i.e. 李 is li so I am able to type l then i and then the Chinese character 李 appears. Is there anyway to get around this? Any help would be greatly appreciated. Thanks
回答1:
Try to set the keyboard type of the input field
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectZero];
tf.keyboardType = UIKeyboardTypeASCIICapable;
回答2:
used this
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
if(stringIsValid){
return yes;
else
return no;
}
来源:https://stackoverflow.com/questions/27961910/how-do-i-restrict-uitextfield-to-english-only-stopping-chinese-pinyin-input