1. Define an event:
-(Ibaction) Limitlength: (Uitextfield *) sender{bool ischinese;//Determine if the current input method is Chinese if ([[[Uitextinputmode Currentinputmode] Primarylanguage] isequaltostring: @ "en-us"]) {Ischinese = false; } else {Ischinese = true; } if (sender = = self.txtname) {//8-bit nsstring *str = [[self.txtname text] Stringbyreplacingoccurrenc esofstring:@ "?" withstring:@ ""]; if (Ischinese) {//Chinese Input method Uitextrange *selectedrange = [Self.txtname markedtextrange]; Get the highlighted part uitextposition *position = [Self.txtname positionFromPosition:selectedRange.start offset:0]; If there are no highlighted words, the word count and limit if (!position) {NSLog (@ "kanji") are entered. if (str.length>=9) {nsstring *strnew = [NSString stringwithstring:str]; [Self.txtname settext:[strnew Substringtoindex:8]; }} else {NSLog (@ "entered in English has not been translated into the status of Chinese characters"); }}else{NSLog (@ "str=%@; this time =%d", str,[str length]); if ([str length]>=9) {nsstring *strnew = [NSString stringwithstring:str]; [Self.txtname settext:[strnew Substringtoindex:8]; } } }}
2. Add a listen event to the Uitextfield control:
Uicontroleventeditingchanged
[Self.txtname addtarget:self Action: @selector (limitlength:) forcontrolevents:uicontroleventeditingchanged];
IOS 7/8--uitextfield dynamically limits the number of words entered