1. Define an event:
-(IBAction) limitLength :( UITextField *) sender {bool isChinese; // determines whether the current input method is Chinese. if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @ "en-US"]) {isChinese = false;} else {isChinese = true;} if (sender = self.txt Name) {// 8-bit NSString * str = repeated bytes self.txt Name text] stringByReplacingOccurrencesOfString :@"? "WithString: @" "]; if (isChinese) {// UITextRange * selectedRange = {self.txt Name markedTextRange] in the Chinese Input Method; // obtain the highlighted UITextPosition * position = {self.txt Name positionFromPosition: selectedRange. start offset: 0]; // if (! Position) {NSLog (@ ""); if (str. length >=9) {NSString * strNew = [NSString stringWithString: str]; incluself.txt Name setText: [strNew substringToIndex: 8];} else {NSLog (@ "The entered English language has not been converted into Chinese characters") ;}} else {NSLog (@ "str = % @; length = % d ", str, [str length]); if ([str length]> = 9) {NSString * strNew = [NSString stringWithString: str]; then self.txt Name setText: [strNew substringToIndex: 8] ;}}}
2. Add a listening event to the UITextField control:
//UIControlEventEditingChanged [self.txtName addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];