UITextView字數限制-防止粘貼超過限制

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text

{

? ? //http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield

? ? // Prevent crashing undo bug – see note below.

? ? if(range.length+ range.location> textView.text.length)

? ? {

? ? ? ? returnNO;

? ? }

? ? NSUIntegerlength = [textView.textlength] + [textlength] - range.length;

? ? returnlength <=PA_WORD_LIMIT;

//? ? Before the text field changes, the UITextView asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it's current length and the string length we're inserting, minus the range length. If this value is too long (more than 25 characters in this example), return NO to prohibit the change.

//? ? ? ?

//? ? ? ? When typing in a single character at the end of a text field, the range.location will be the current field's length, and range.length will be 0 because we're not replacing/deleting anything. Inserting into the middle of a text field just means a different range.location, and pasting multiple characters just means string has more than one character in it.

//? ? ? ?

//? ? ? ? Deleting single characters or cutting multiple characters is specified by a range with a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.

//? ? ? ? A note on the crashing "undo" bug

//? ? ? ?

//? ? ? ? As is mentioned in the comments, there is a bug with UITextView that can lead to a crash.

//? ? ? ?

//? ? ? ? If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application's undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the UITextView will attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn't exist.

//? ? ? ?

//? ? ? ? Fortunately you can protect the UITextView from killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,815評論 0 23
  • 一、好句: 枯燥的日子,將心漸漸磨出了平靜,于是,學會了習慣,也學會了把握。人生就是一場匆忙的路過,優雅不失訓練出...
    吳世浩閱讀 13,287評論 2 1
  • 當晨曦的曙光刺痛明媚的雙眼, 當暮春的麥秸顫笑無盡的嘆息, 我依然固執地踏破風月的痕跡, 用浪漫的詩句為你寫下:畫...
    初歸a閱讀 406評論 0 1
  • 重要: 如果有浮動,那么父元素必須清除浮動 有inline-block,需要注意兩個inline-block元素之...
    放風箏的小小馬閱讀 215評論 0 0
  • 畫卷剪不斷 風卷殘云弦 留戀卻往返 執手看淚眼 秋雨朦朧 涼了思念 花開花敗 斷了羈絆 無可奈何 了卻年年 不曾追...
    注定被遺忘的孤獨閱讀 177評論 0 0