1、定義一個事件:
-(IBAction)limitLength:(UITextField *)sender { bool isChinese;//判斷當前輸入法是否是中文 if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @"en-US"]) { isChinese = false; } else { isChinese = true; } if(sender == self.txtName) { // 8位 NSString *str = [[self.txtName text] stringByReplacingOccurrencesOfString:@"?" withString:@""]; if (isChinese) { //中文輸入法下 UITextRange *selectedRange = [self.txtName markedTextRange]; //獲取高亮部分 UITextPosition *position = [self.txtName positionFromPosition:selectedRange.start offset:0]; // 沒有高亮選擇的字,則對已輸入的文字進行字數統計和限制 if (!position) { NSLog(@"漢字"); if ( str.length>=9) { NSString *strNew = [NSString stringWithString:str]; [self.txtName setText:[strNew substringToIndex:8]]; } } else { NSLog(@"輸入的英文還沒有轉化為漢字的狀態"); } }else{ NSLog(@"str=%@; 本次長度=%d",str,[str length]); if ([str length]>=9) { NSString *strNew = [NSString stringWithString:str]; [self.txtName setText:[strNew substringToIndex:8]]; } } } }
//UIControlEventEditingChanged [self.txtName addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];