在做限制文本输入长度的时候遇到很多坑,下面就是很好的解决了文本输入长度限制的方法:
-textFiled的字数限制,一个汉字相当于2字符:
[_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField
{
NSInteger inter = 5;//限制文本输入不超过5个汉字
NSNumber *number;
if ([self IsChinese:textField.text]==0) {//判断输了多少汉字
NSInteger number1 = inter*2;
number = [NSNumber numberWithInteger:number1] ;
}else{
if ([self IsChinese:textField.text] <= inter) {
NSInteger nuber2 = inter*2 - [BJSounds IsChinese:textField.text]*2 + [BJSounds IsChinese:textField.text];
number = [NSNumber numberWithInteger:nuber2];
}else{
number = [NSNumber numberWithInteger:inter];
}
}
if (number && textField.text.length > [number integerValue] && textField.markedTextRange == nil) {
textField.text = [textField.text substringWithRange: NSMakeRange(0, [number integerValue])];
}
}
- (NSInteger)IsChinese:(NSString *)str {
int j = 0;
for(int i=0; i< [str length];i++){
int a = [str characterAtIndex:i];
if( a > 0x4e00 && a < 0x9fff)
{
j++;
}
}
return j;
}
网友评论