直接上代碼
- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString*)text
{
UITextRange*selectedRange = [textView markedTextRange];
//獲取高亮部分
UITextPosition*pos = [textView positionFromPosition:selectedRange.startoffset: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 = [textViewoffsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
NSRange offsetRange =NSMakeRange(startOffset, endOffset - startOffset);
if(offsetRange.location
returnYES;
}
else
{
returnNO;
}
}
NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:rangewithString:text];
NSIntege rcaninputlen =MAX_LIMIT_NUMS- comcatstr.length;
if(caninputlen >=0)
{
returnYES;
}
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 =@"";
//判斷是否只普通的字符或asc碼(對(duì)于中文和表情返回NO)
BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
if(asc) {
s = [text substringWithRange:rg];//因?yàn)槭莂scii碼直接取就可以了不會(huì)錯(cuò)
}
else
{
__block NSInteger idx =0;
__block NSString*trimString =@"";//截取出的字串
//使用字符串遍歷环戈,這個(gè)方法能準(zhǔn)確知道每個(gè)emoji是占一個(gè)unicode還是兩個(gè)
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring,NSRangesubstringRange,NSRangeenclosingRange,BOOL* stop) {
if(idx >= rg.length) {
*stop =YES;//取出所需要就break,提高效率
return;
}
trimString = [trimString stringByAppendingString:substring];
idx++;
}];
s = trimString;
}
//rang是指從當(dāng)前光標(biāo)處進(jìn)行替換處理(注意如果執(zhí)行此句后面返回的是YES會(huì)觸發(fā)didchange事件)
[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
//既然是超出部分截取了舷蟀,哪一定是最大限制了乐横。
self.lbNums.text= [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
}
returnNO;
}
}
- (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)
{
//截取到最大位置的字符(由于超出截部分在should時(shí)被處理了所在這里這了提高效率不再判斷)
NSString*s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
[textViewsetText:s];
}
//不讓顯示負(fù)數(shù)
self.lbNums.text= [NSString stringWithFormat:@"%ld/%d",existTextNum,MAX_LIMIT_NUMS];
}