How do I restrict UITextField to English only? (Stopping Chinese pinyin input)

若如初见. 提交于 2019-12-11 09:30:00

问题


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

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