Reputation: 3572
I'm trying to prevent Chinese (or otherwise, all non-ascii characters) from being input into a UITextField. As seen in other posts, I implemented textField:shouldChangeCharactersInRange:replacementString:
, but when I enter Chinese words from the word-list-thing that appears on top of the keyboard after you press a few keys, the textField:shouldChangeCharactersInRange:replacementString:
method does not fire.
Any ideas?
Upvotes: 2
Views: 1258
Reputation: 6287
A workaround you can take is to use:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
then in your function:
- (void)textChanged:(NSNotification *)notification{
//remove observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
//change your textfield's value here e.g.
myTextField.text = [MyUtils removeNonAsciiChar:myTextField.text];
//add observer again
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
Note however that this is more costly since you will be replacing the entire string everytime, but it should be okay if you're not expecting a very long string.
Upvotes: 2