? ? ? ? Today was the day of the problem. In the Uitextfield delegate method, various judgments. The result is still a bug. The most obvious is the Chinese input mode, the Lenovo input can break the word limit.
Today we find a way to register the Observer uitextfieldtextdidchangenotification. If the Uitextfield content changes, count the words and judge.
Take three steps:
First step: Register the Observer.
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (textfielddidchange:) Name: Uitextfieldtextdidchangenotification Object:_partnametextfield];
????? Step two: Ways to implement the observer.?
-(void) Textfielddidchange: (nsnotification *) obj{Uitextfield * TextField = (Uitextfield *) Obj.object; NSString *tobestring = Textfield.text; Keyboard input mode (the way to determine the input mode is iOS7 later use, if you want to do compatible, Google) Nsarray * Currentar = [Uitextinputmode activeinputmodes]; Uitextinputmode * current = [Currentar firstobject]; if ([Current.primarylanguage 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]; If there is no highlighted word, the word count and limit if (!position) {if (Tobestring.length > Ktextfieldlengthlimit Textfield.text = [tobestring substringtoindex:ktextfieldlengthlimit]; [Self Showerrortips:nil message:nslocalizedstring (@ "Textfield_length_limit", nil)];//This method is the third-party warning box that I introduced. Readers can complete their own warning pop-up window. }}//With a highlighted string, the text is temporarily not counted and restricted else{ }}//In addition to the Chinese input method directly to its statistical restrictions, regardless of other languages else{if (Tobestring.length > Ktextfieldlengthlimit) { Textfield.text = [tobestring substringtoindex:ktextfieldlengthlimit]; } } }
? ? ? ? Step three: Destroy the Observer.
-(void) dealloc{ [[Nsnotificationcenter Defaultcenter] removeobserver:self name: Uitextfieldtextdidchangenotification Object:_partnametextfield];}
?
? ? ? ? All right, finish the call.
?
?
Uitextfield Limit Word Count method