如何限制UITextField的输入长度
1.给textField添加UIControlEventEditingChanged的事件处理
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
2.在方法:textFieldDidChange中处理逻辑
NSString *toBeString = TextField.text;
NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;
//简体中文输入,包括简体拼音,健体五笔,简体手写
if([lang isEqualToString:@"zh-Hans"] || [lang isEqualToString:@"zh-Hant"]){
UITextRange *selectedRange = [TextField markedTextRange];
UITextPosition *position = [TextField positionFromPosition:selectedRange.start offset:0];
if (!position){//非高亮(高亮表示只显示了汉字的拼音字母,汉字还未输入进去的状态)
if (toBeString.length > maxLength) {
TextField.text = [toBeString substringToIndex:maxLength];
}
}
}else{//中文输入法以外
if (toBeString.length > maxLength) {
TextField.text = [toBeString substringToIndex:maxLength];
}
}