限制TextView的字数

  • Post author:
  • Post category:其他


效果图

程序如下:

方法一:

@property (nonatomic, copy) void(^txtViewBlock)(NSString *desTxt);

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.desTextView.layer.borderWidth = 1;
    self.desTextView.layer.borderColor = UIColorFromRGB(0xebecf0).CGColor;
    self.desTextView.layer.masksToBounds = YES;
    
    self.desTextView.delegate = self;
    //设置通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextView:) name:UITextViewTextDidChangeNotification object:nil];
    // Initialization code
}

- (void)changeTextView:(id)sender {
    if (_txtViewBlock) {
        _txtViewBlock(self.desTextView.text);
    }
}

- (void)decription:(void (^)(NSString *))txtViewBlock {
    _txtViewBlock = txtViewBlock;
}

- (void)textViewDidChange:(UITextView *)textView {
    NSInteger number = [textView.text length];
    if (number>0) {
        _placeholderLabel.hidden = YES;
    }else {
        _placeholderLabel.hidden = NO;
    }
    
    if (number > 255) {
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"字符个数不能大于50" delegate:self cancelButtonTitle:@"确定"otherButtonTitles:nil];
        //        [alert show];
        textView.text = [textView.text substringToIndex:255];
        number = 255;
    }
    
    self.textNum.text = [NSString stringWithFormat:@"%ld/255", (long)number];
}
#pragma mark -UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString *content = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - content.length;

    if (caninputlen >= 0)
    {
        self.lengthLabel.text = [NSString stringWithFormat:@"%ld/300", (long)content.length];
        if (_contentBlock) {
            _contentBlock(content);
        }
        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 = [text substringWithRange:rg];
            
            content = [textView.text stringByReplacingCharactersInRange:range withString:s];
            [textView setText:content];
            
            if (_contentBlock) {
                _contentBlock(content);
            }
            
            self.lengthLabel.text = [NSString stringWithFormat:@"%ld/300", (long)content.length];
        }
        return NO;
    }
}


转载于:https://my.oschina.net/u/2519763/blog/743546