When using the Pinyin input method, the last parameter in the delegate method string accepts the input letter instead of the selected Chinese character, and the result is that when you want to enter the text "I am Programming", enter the Pinyin "Wozaibiancheng", each input letter will enter the delegate method, The character length of the statistic is the length of the letter, in fact the character has not exceeded the limit length, but the length of the letter exceeds the input.
The Chinese way to control the input length is as follows:
1. Register notification
[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (textfilededitchanged:) Name: Uitextfieldtextdidchangenotification Object:self.customTextField];
2. Implement the Listening method
-(void) textfilededitchanged: (nsnotification *) obj{ Uitextfield *textfield = (Uitextfield *) Obj.object; NSString *tobestring = Textfield.text; NSString *lang = [[UIApplication sharedapplication] textinputmode].primarylanguage; Keyboard Input mode if ([Lang isequaltostring:@ "Zh-hans"]) {//Simplified Chinese input, including simplified pinyin, fitness wubi, simplified handwriting uitextrange *selectedrange = [ TextField Markedtextrange]; Get the highlighted part uitextposition *position = [TextField positionFromPosition:selectedRange.start offset:0]; No highlighted words, word count and limit if (!position) { if (Tobestring.length > 5) { Textfield.text = [ Tobestring substringtoindex:5]; } } There is a highlighted string, then the text is not counted and limited else{ } } //Chinese Input method directly to its statistical restrictions, regardless of other languages else{ if ( Tobestring.length > 5) { Textfield.text = [tobestring substringtoindex:5];}}
3. In the Dealloc
-(void) dealloc{ [[Nsnotificationcenter defaultcenter]removeobserver:self Name: Uitextfieldtextdidchangenotification Object:self.customTextField];}
Similarly, when using Uitextview, the same approach is used if you want to restrict Chinese input.
[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (textvieweditchanged:) Name: Uitextviewtextdidchangenotification Object:mytextview];
IOS Chinese input Length control