// 限制textfield輸入字?jǐn)?shù)
- (NSString *)limitTextFieldNum:(UITextField *)textField withNum:(NSInteger)maxNum{
? ?NSInteger kMaxLength = maxNum;
? ? NSString *toBeString = textField.text;
? ? NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage
? ? if ([lang isEqualToString:@"zh-Hans"]) { //中文輸入
? ? ? ? UITextRange *selectedRange = [textField markedTextRange];
? ? ? ? //獲取高亮部分
? ? ? ? UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
? ? ? ? if (!position) {// 沒有高亮選擇的字,則對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計(jì)和限制
? ? ? ? ? ? if (toBeString.length > kMaxLength) {
? ? ? ? ? ? ? ? textField.text = [toBeString substringToIndex:kMaxLength];
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? else{//有高亮選擇的字符串,則暫不對(duì)文字進(jìn)行統(tǒng)計(jì)和限制
? ? ? ? ? ? if (toBeString.length > kMaxLength) {
? ? ? ? ? ? ? ? textField.text = [toBeString substringToIndex:kMaxLength];
? ? ? ? ? ? }
? ? ? ? }
? ? }else{//中文輸入法以外的直接對(duì)其統(tǒng)計(jì)限制即可,不考慮其他語種情況
? ? ? ? if (toBeString.length > kMaxLength) {
? ? ? ? ? ? textField.text = [toBeString substringToIndex:kMaxLength]; ?
? ? ? ? ?}
?}
? ? return textField.text;
}