- (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.
}
UITextView字数限制-防止粘贴超过限制
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...