[iOS]iOS7系統(tǒng)下multistage text input(中文輸入法)下UITextView的內容長度限制(二)

前情描述

[iOS]UITextView限制字數的寫法(一)
需要在iOSApp中完成一個限制字符個數60個的textView編輯框,一般實現的方式是

- (void)textViewDidChange:(UITextView *)textView
{  
    if ([textView.text length] > 60) 
    { 
        textView.text = [textView.text substringWithRange:NSMakeRange(0, 60)]; 
        [textView.undoManager removeAllActions]; 
        [textView becomeFirstResponder]; 
        return; 
    }
}

遇到的問題

但是在iOS7系統(tǒng)中,粘貼完達到限制個數的字符個數后,可以退格刪除,再使用中文輸入法進行輸入,這時候進入multistage text input模式,會觸發(fā)的問題

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds' 

解決方案

由于中文輸入法的鍵盤上有聯想、推薦的功能,所以可能導致文本內容長度上有些不符合預期,導致越界,所以可以參考?以下做下處理:
添加textView.markedTextRange == nil聯想提示條的判斷

- (void)textViewDidChange:(UITextView *)textView
{  
    if (textView.markedTextRange == nil && [textView.text length] > 60) 
    { 
        textView.text = [textView.text substringWithRange:NSMakeRange(0, 60)]; 
        [textView.undoManager removeAllActions]; 
        [textView becomeFirstResponder]; 
        return; 
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容