监听
[self.textTF addTarget:self action:@selector(textFieldTextChanged:) forControlEvents: UIControlEventEditingChanged];
- (void)textFieldTextChanged:(UITextField *)textField{
NSString *str = textField.text;
//中文输入法下
UITextRange *selectedRange = [self.textTF markedTextRange];
//高亮部分
UITextPosition *postion = [self.textTF positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!postion) {
if (str.length > 5 ){ //判断字符是否超过
self.textTF.text = [str substringToIndex:6];
}
}
}
//获取字符长度,中文为2
- (NSInteger )strLength:(NSString *)str {
NSInteger length = 0;
for(int i=0; i< [str length];i++) {
int a = [str characterAtIndex:i];
if( a > 0x4e00 && a < 0x9fff){//判断输入的是否是中文
length = length + 2;
} else {
length = length + 1;
}
}
return length;
}
网友评论