zoukankan      html  css  js  c++  java
  • 对textView 的输入个数进行判断

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

    {
        /*
        if ([text isEqualToString:@" "])
        {
            [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;
     }
    }
  • 相关阅读:
    Android应用程序组件Content Provider在应用程序之间共享数据的原理分析
    Android录制声音(二)录音输输出格式
    Firemacs:像垄断 Emacs 一样垄断 Firefox
    超棒的 KDE 面板小序次-Kirocker Music Display
    特征化设置你的linux环境
    软响铃 ── 把 beep 换成音乐
    简化 Picasa 图片上传
    Moonlight:Linux 平台上的 Silverlight
    Wine 0.9.39
    本钱与linux
  • 原文地址:https://www.cnblogs.com/-ios/p/4670052.html
Copyright © 2011-2022 走看看