Search code examples
iosxcodeuitextfielduitextfielddelegate

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


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


Solution

  • Try to set the keyboard type of the input field

    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectZero];
    tf.keyboardType = UIKeyboardTypeASCIICapable;