###textfield监听输入汉字数量
- 首先我们给textfield添加一个事件,当文字改变的时候调用
[self.nameTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
- 实现这个方法,监听输入汉字的数量
- (void)textFieldChange{
// 得到当前输入的文字
NSString *toBeString = self.nameTextField.text;
// 获取当前文字的类型
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
if([lang isEqualToString:@"zh-Hans"]){ //简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [self.nameTextField markedTextRange];
//获取高亮状态
UITextPosition *position = [self.nameTextField positionFromPosition:selectedRange.start offset:0];
if (!position){//非高亮
if (toBeString.length > 5) {
[UIAlertView alertViewWithTitle:@"提醒" message:@"名字长度不能超过5位" cancelButtonTitle:@"确定"];
self.nameTextField.text = [toBeString substringToIndex:5];
}
}
}else{//中文输入法以外
[UIAlertView alertViewWithTitle:@"提醒" message:@"名字只能输入中文" cancelButtonTitle:@"确定"];
self.nameTextField.text = [toBeString substringToIndex:toBeString.length - 1];
}
}