关于键盘输入中文控制字数 (找了很久,最好的写法)真是完美
- (void)textchanged:(NSNotification *)noti{
UITextField *textfield = (UITextField *)noti.object;
NSInteger kMaxLength = 40;
if (textfield.tag == kSuggestAdressFieldTag) {
kMaxLength = 20;
}
NSString *toBeString =textfield.text;
NSString *lang;
if (IS_OS_7_OR_LATER) {
lang = [[textfield textInputMode] primaryLanguage];
}else{
lang = [[UITextInputMode currentInputMode] primaryLanguage];//iOS7以后弃用了
}
if([lang isEqualToString:@"zh-Hans"]){ //简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textfield markedTextRange];
UITextPosition *position = [textfield positionFromPosition:selectedRange.start offset:0];
if (!position){//非高亮
if (toBeString.length > kMaxLength) {
textfield.text = [toBeString substringToIndex:kMaxLength];
}
}
}else{//中文输入法以外
if (toBeString.length > kMaxLength) {
textfield.text = [toBeString substringToIndex:kMaxLength];
}
}
}