限制textView的长度 对textView 的输入个数进行判断

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    /*
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder]; return NO;
    }else if([textView.text length] >= 30 && ![text isEqualToString:@""]){
        return NO;
    }
     
    return YES;
     */
//    return YES;
    int _textMaxLength = 60;
    if (_textMaxLength == 0) {
        return YES;
    }
     
    void(^dealWithTexts)(void) = ^() {
        NSString *textInField = [textView.text substringToIndex:range.location];
        int inputedHanzi = [[textInField componentsMatchedByRegex:@"[\u4e00-\u9fa5]"] count];
        int inputedLength = textInField.length + inputedHanzi;
        int allowedLength = _textMaxLength - inputedLength;
        int length = 0;
        int stop = text.length;
        for (int i = 0; i < text.length; i++) {
            NSString *c = [text substringWithRange:NSMakeRange(i, 1)];
            if ([c isMatchedByRegex:@"[\u4e00-\u9fa5]"]) {
                if (length + 2 > allowedLength) { stop = i; break; }
                length += 2;
            } else {
                if (length + 1 > allowedLength) { stop = i; break; }
                length++;
            }
        }
        NSString *shouldAddedString = [text substringToIndex:stop];
        NSString *textShouldInField = [NSString stringWithFormat:@"%@%@",textInField,shouldAddedString];
        [textView performSelector:@selector(setText:) withObject:textShouldInField afterDelay:0.0];
    };
     
    if ( 1 == range.length && text.length == 0)
 {
  return YES; //删除
 }
    else if (range.length > 1) {
        dealWithTexts();
        return YES;
    }
 else
 {
  NSString * text2 = [textView.text stringByReplacingCharactersInRange:range withString:text];
        text2 = [text2 stringByReplacingOccurrencesOfRegex:@"[\u4e00-\u9fa5]" withString:@"##"];
        int symbol = [[text2 componentsMatchedByRegex:@"\u2006"] count];
  if ( _textMaxLength > 0 && text2.length - symbol > _textMaxLength )
  {
            if (text.length > 1) {
                dealWithTexts();
                return YES;
            }
   return NO;
  }
  return YES;
 }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值