字数限制的问题点在于汉语可以无限汉语联想词汇,导致字数限制对于汉字输入就失去的作用。我们的做法是监听键盘联想出来的汉子,将其统计:
1 在viewDidLoad里面监听文本变化的通知
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged:) name:UITextFieldTextDidChangeNotification object:detailAddress];
}
2 实现这个textViewEditChanged:方法
// 监听文本改变
-(void)textViewEditChanged:(NSNotification *)obj{
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
NSUInteger maxLength = MaxNumberOfDescriptionChars-curZone.text.length-1;//加上自动定位的地址,上限是45个汉字
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > maxLength) {
textField.text = [toBeString substringToIndex:maxLength];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if (toBeString.length > maxLength) {
textField.text = [toBeString substringToIndex:maxLength];
}
}
}
3 当然,你还需要在textField的delegate方法里面做正常的限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@""])
{
return YES;
}
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (detailAddress == textField)
{
NSUInteger maxLength = MaxNumberOfDescriptionChars;//设置文字上限
if ([toBeString length] > maxLength) {
textField.text = [toBeString substringToIndex:maxLength];
[Utils showToastWithText:@"超过最大字数限制"];
return NO;
}
}
return YES;
}
|