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...
    又是夜半惊坐起阅读 13,402评论 0 23
  • 一、好句: 枯燥的日子,将心渐渐磨出了平静,于是,学会了习惯,也学会了把握。人生就是一场匆忙的路过,优雅不失训练出...
    吴世浩阅读 14,518评论 2 1
  • 当晨曦的曙光刺痛明媚的双眼, 当暮春的麦秸颤笑无尽的叹息, 我依然固执地踏破风月的痕迹, 用浪漫的诗句为你写下:画...
    初归a阅读 3,021评论 0 1
  • 重要: 如果有浮动,那么父元素必须清除浮动 有inline-block,需要注意两个inline-block元素之...
    放风筝的小小马阅读 1,443评论 0 0
  • 画卷剪不断 风卷残云弦 留恋却往返 执手看泪眼 秋雨朦胧 凉了思念 花开花败 断了羁绊 无可奈何 了却年年 不曾追...
    注定被遗忘的孤独阅读 1,189评论 0 0