Dennis Dennis - 1 year ago 284
iOS Question

UITextfield limit The Chinese characters length

#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;


I used this methods to limit the length of the textfield. It worked when iputing the usual
characters. Unfortunately, it doesn't work when inputing the Chinese characters.

Answer Source

When inputing some languages that uses a input method, the input of your pinyin makes -textField: shouldChangeCharactersInRange:replacementString get called, and when you select your Chinese characters, another call to this method occurs, sadly, you can't distinguish whether this method is called by inputing pinyin or changing pinyin to Chinese.

So it's always better to allow user input more characters than you limit, but not allowing user to submit the input. You can see how Weibo does this when user input there feed.

I'v found another solution: You can use @property markedTextRange, by which you can get if there is any Pinyin that is waiting for Chinese character selection, if there is any, you don't limit the input string length, and once user turn all Pinyin into Chinese character, you can truncate the Chinese string upon your limit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download