Counting words
1, First register monitoring
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (textvieweditchanged:) name:@ " Uitextviewtextdidchangenotification "Object:_textview";
2. Implement Monitoring method
-(void) textvieweditchanged: (nsnotification *) obj{Uitextview *textfield = (Uitextview *) Obj.object; NSLog (@ "========%@", Textfield.text); NSString *tobestring = Textfield.text; NSString *lang = [[Uitextinputmode currentinputmode] primarylanguage]; Keyboard input mode if ([Lang isequaltostring:@ "Zh-hans"]) {//Simplified Chinese input, including simplified pinyin, fitness wubi, simplified handwriting uitextrange *selectedrange = [text Field 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 >) {textField) for typed text . Text = [tobestring substringtoindex:10]; [[[Uialertview alloc] initwithtitle:@ "DSFSA" message:@ "msg" Delegate:self cancelbuttontitle:nil otherbuttontitles:@ " Sure ", nil) show]; [Self.textview Resignfirstresponder]; }}//With a highlighted string, the text is temporarily not counted and restrictedelse{}}//In addition to the Chinese input method directly to its statistical restrictions, regardless of other languages else{if (Tobestring.length > 10) { Textfield.text = [tobestring substringtoindex:10]; [[[Uialertview alloc] initwithtitle:@ "DSFSA" message:@ "msg" Delegate:self cancelbuttontitle:nil otherbuttontitles:@ " Sure ", nil) show]; } } }
3, the final cancellation of the supervisor listener
-(void) dealloc{ [[Nsnotificationcenter Defaultcenter] removeobserver:self name:@ " Uitextviewtextdidchangenotification "Object:_textview";}
TextView word count when inputting Chinese and highlighting English input method