iOS UITextView 限制字数+显示字数(转载)

2016-04-11  本文已影响110人  孤胆走天涯

#pragma mark UITextViewDelegate

- (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 = [text substringWithRange:rg];

[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

//既然是超出部分截取了,哪一定是最大限制了。

labLimitNum.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];

}

return NO;

}

}

- (void)textViewDidChange:(UITextView *)textView

{

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)

{

//截取到最大位置的字符

NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];

[textView setText:s];

}

//不让显示负数

labLimitNum.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];

}

上一篇下一篇

猜你喜欢

热点阅读