1

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

3 Answers 3

9

Try to set the keyboard type of the input field

UITextField *tf = [[UITextField alloc] initWithFrame:CGRectZero];
tf.keyboardType = UIKeyboardTypeASCIICapable;
2
  • 2
    This is wrong. A user can still paste anything into the text field.
    – rmaddy
    Dec 15, 2016 at 17:21
  • 1
    @rmaddy It can be detected through a validation check though for example, upon form submission.
    – mobby
    Nov 6, 2020 at 11:17
1

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;

}
1
  • tried this and it won't work. Think it is because with pinyin you are actually typing in English first before the Chinese character appears and shouldChangeCharactersInRange is called after every keypress i.e an english character...
    – Kex
    Jan 15, 2015 at 11:17
0

Swift 5:

just change keyboardType to asciiCapable

englishNameTextField.keyboardType = .asciiCapable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.