textField和textView的輸入字數最大限制

textField最大字數限制:spa

先給textField添加事件code

    [cell.rightTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

實現方法:orm

- (void)textFieldDidChange:(UITextField *)textField{
    UITextRange *selectedRange = textField.markedTextRange;
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        // 沒有高亮選擇的字
        // 1. 過濾非漢字、字母、數字字符
        textField.text = [self filterCharactor:textField.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
        // 2. 截取
        if (textField.text.length >= 30) {
            textField.text = [textField.text substringToIndex:30];
        }
    } else {
        // 有高亮選擇的字 不作任何操做
    }
}

// 過濾字符串中的非漢字、字母、數字
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *filterText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
    return result;
}

/** 字數限制 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // 解決當雙擊切換標點時誤刪除正常文字 bug
    NSString *punctuateSring = @",。?!._@/#";
    if (range.length == 0 && string.length == 1 && [punctuateSring containsString:string]) {
        return NO;
    }
    
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    NSInteger pointLength = existedLength - selectedLength + replaceLength;
    //超過16位 就不能在輸入了
    
    NSInteger maxLength = 1000;
    // 暱稱
    if (textField.tag == 4422) {
        maxLength = 30;
    }
    // 中文名
    else if (textField.tag == 4444) {
        maxLength = 30;
    }
    // QQ號
    else if (textField.tag == 4455) {
        maxLength = 20;
    }
    
    if (pointLength > maxLength) {
        return NO;
    }else{
        return YES;
    }
}

 

textView的輸入字數最大限制:blog

#define MAX_LIMIT_NUMS     128
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    UITextRange *selectedRange = [textView markedTextRange];
    //獲取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //獲取高亮部份內容
    //NSString * selectedtext = [textView textInRange:selectedRange];
    
    //若是有高亮且當前字數開始位置小於最大限制時容許輸入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < MAX_LIMIT_NUMS) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止當text.length + caninputlen < 0時,使得rg.length爲一個非法最大正數出錯
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = @"";
            //判斷是否只普通的字符或asc碼(對於中文和表情返回NO)
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            if (asc) {
                s = [text substringWithRange:rg];//由於是ascii碼直接取就能夠了不會錯
            }
            else
            {
                __block NSInteger idx = 0;
                __block NSString  *trimString = @"";//截取出的字串
                //使用字符串遍歷,這個方法能準確知道每一個emoji是佔一個unicode仍是兩個
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                          
                                          if (idx >= rg.length) {
                                              *stop = YES; //取出所須要就break,提升效率
                                              return ;
                                          }
                                          
                                          trimString = [trimString stringByAppendingString:substring];
                                          
                                          idx++;
                                      }];
                
                s = trimString;
            }
            //rang是指從當前光標處進行替換處理(注意若是執行此句後面返回的是YES會觸發didchange事件)
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            //既然是超出部分截取了,哪必定是最大限制了。
            //            problemDetailLab.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
        }
        return NO;
    }
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.getAddModel.DetailedAdd = textView.text;
    
    UITextRange *selectedRange = [textView markedTextRange];
    //獲取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //若是在變化中是高亮部分在變,就不要計算字符了
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > MAX_LIMIT_NUMS)
    {
        //截取到最大位置的字符(因爲超出截部分在should時被處理了所在這裏這了提升效率再也不判斷)
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        
        [textView setText:s];
    }
    
    //不讓顯示負數 口口日
    //    problemDetailLab.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}
相關文章
相關標籤/搜索