Last active
September 13, 2016 12:53
-
-
Save guodong000/e29a5158431f9b5055acfcca20028827 to your computer and use it in GitHub Desktop.
限制UITextView的最大文字长度
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MAX_LENGTH 15 // Whatever your limit is | |
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text | |
{ | |
NSUInteger newLength = (textView.text.length - range.length) + text.length; | |
if(newLength <= MAX_LENGTH) | |
{ | |
return YES; | |
} else { | |
NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length); | |
textView.text = [[[textView.text substringToIndex:range.location] | |
stringByAppendingString:[text substringToIndex:emptySpace]] | |
stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]]; | |
return NO; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment