TextField、TextViewT文字实时长度

文字变化的代理方法里面

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //限制文字个数输入
    NSInteger existedLength = textView.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = text.length;
    NSInteger currentLength = existedLength - selectedLength + replaceLength;
    NSLog(@"当前文字长度:%ld", currentLength);
    if (currentLength > 20) {
        return NO;
    }
    
    //实时文字
    NSString *allString;
    if (text.length == 0 && textView.text.length > 0) {
        allString = [textView.text substringToIndex:textView.text.length-1];
    }else{
        allString = [NSString stringWithFormat:@"%@%@",textView.text, text];
    }
    NSLog(@"当前输入的文字:%@", allString);
    
    return YES;
}

你可能感兴趣的:(TextField、TextViewT文字实时长度)