处理textField中的非ASCII字符:shouldChangeCharactersInRange:replacementString: [英] Handling non-ascii characters in textField:shouldChangeCharactersInRange:replacementString:
问题描述
我试图防止中文(或其他所有非ASCII字符)被输入到UITextField。如在其他帖子中看到的,我实现了 textField:shouldChangeCharactersInRange:replacementString:
,但是当我从在键盘顶部出现的word-list-thing按几个键, textField:shouldChangeCharactersInRange:replacementString:
方法不会触发。
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.
任何想法?
推荐答案
使用:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
然后在您的函数中:
- (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.
这篇关于处理textField中的非ASCII字符:shouldChangeCharactersInRange:replacementString:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!