#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];
//獲取高亮部分內(nèi)容
//NSString * selectedtext = [textView textInRange:selectedRange];
//如果有高亮且當(dāng)前字?jǐn)?shù)開(kāi)始位置小于最大限制時(shí)允許輸入
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;
//防止當(dāng)text.length + caninputlen < 0時(shí)肴裙,使得rg.length為一個(gè)非法最大正數(shù)出錯(cuò)
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];
//如果在變化中是高亮部分在變蜻懦,就不要計(jì)算字符了
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];
}
//不讓顯示負(fù)數(shù)
labLimitNum.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}