举个例子:限制输入字符为200
#pragma mark - TextView Delegate
-(void)textViewDidChange:(UITextView*)textView{
if ([textView.text length] == 0) {
[self.placeStrLabel setHidden:NO];
}else{
[self.placeStrLabel setHidden:YES];
}
[self updateRemainCount];
if (_textViewBlock) {
_textViewBlock(textView.text);
}
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//如果在变化中是高亮部分在变,就不要计算字符了
if(selectedRange && pos) {return;}
self.lengthLabel.text = [NSString stringWithFormat:@"%lu/200", (unsigned long)textView.text.length];
if( (unsigned long)textView.text.length>self.MaxCount) {
// 对超出的部分进行剪切
textView.text= [textView.text substringToIndex:self.MaxCount];
self.lengthLabel.text = @"200/200";
}
}
- (void)updateRemainCount {
long count = MAX(0, (int)(0 + self.messageTextView.text.length));
self.lengthLabel.text = [NSString stringWithFormat:@"%ld/%ld",count,(long)self.MaxCount];
}
网友评论