#define MAXLENGTH 12
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.tag == NICKNMAE_TAG) {
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= MAXLENGTH || returnKey;
}
return YES;
}
我使用这种方法来限制文本字段的长度。它在通常的时候起作用了 字符。不幸的是,它在输入中文字符时不起作用。
答案 0 :(得分:2)
当输入一些使用输入法的语言时,拼音的输入会调用-textField: shouldChangeCharactersInRange:replacementString
,当你选择汉字时,会再次调用这种方法,遗憾的是,你无法区分是否通过输入拼音或将拼音更改为中文来调用此方法。
因此,允许用户输入的字符多于限制,但不允许用户提交输入,这总是更好。当用户输入Feed时,您可以看到微博如何做到这一点。
我找到了另一个解决方案: 您可以使用@property markedTextRange,如果有任何拼音等待中文字符选择,您可以获得,如果有,您不限制输入字符串长度,并且一旦用户将所有拼音转换成汉字,你可以根据你的限制截断中文字符串。
答案 1 :(得分:0)
你可以试试这个:
fflush(stdin)
答案 2 :(得分:0)
I have faced the same question and my lovely colleague give an solution.
We need add a target as of UITextField
for UIControlEventAllEditingEvents
.
[textField addTarget:self action:@selector(actionTextFiledDidChange:) forControlEvents:UIControlEventAllEditingEvents];
If textFiled.markedTextRange
is not nil, truncate the text to fit the max length, else leave it.
- (void)actionTextFiledDidChange:(UITextField *)textFiled {
if (textFiled.markedTextRange == nil && textFiled.text.length > MAX_NAME_INPUT_LEN) {
textFiled.text = [textFiled.text substringToIndex:MAX_NAME_INPUT_LEN];
}
}
In the UITextFieldDelegate
, the logic doesn't change.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSInteger newLen = textField.text.length - range.length + string.length;
return (newLen <= MAX_NAME_INPUT_LEN);
}
答案 3 :(得分:0)
swift版本:
yourTextField.addTarget(self
, action: #selector(XXXXX.textFieldValueDidChanged(_:))
, forControlEvents: .EditingChanged)
func textFieldValueDidChanged(textField: UITextField) {
let limit = 100
let txt = textField.text ?? ""
guard nil == textField.markedTextRange else { return }
if txt.characters.count > limit {
let finalTxt = txt.substringWithRange(txt.startIndex..<txt.startIndex.advancedBy(limit))
textField.text = finalTxt
}
}