UITextView实现字数限制

UITextView使用相对较少,研究了下发现代理方法并不多,算是简单控件了。这里针对字数限制功能的开发稍作总结:

//创建UITextView,注意添加代理
    UITextView *textView = [[UITextView alloc]init];
    textView.text = @"占位文字";
    textView.delegate = self;       //UITextViewDelegate
    textView.textColor = hexStringToColor(@"C2C2C2");
    textView.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:textView];
    [textView makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15*layoutBy6());
        make.top.mas_offset(10*layoutBy6());
        make.right.mas_offset(-15*layoutBy6());
        make.bottom.mas_offset(-10*layoutBy6());
    }];
#pragma mark - TextViewDelegate
//输入时自动删除占位文字
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"占位文字"]) {
        textView.text = @"";
    }
}

//当编辑时动态判断是否超过规定字数,这里限制20字
- (void)textViewDidChange:(UITextField *)textView{
    
    if (textView.text.length > 20) {
        textView.text = [textView.text substringToIndex:20];
    }
//这里的_strLengthLbl为动态显示已输入字数,可按情况添加
    _strLengthLbl.text = [NSString stringWithFormat:@"%lu/20",textView.text.length];
}

//编辑结束后如内存为空自动添加占位文字
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"占位文字";
    }
}

你可能感兴趣的:(UITextView实现字数限制)