Applying a Word Limit to a UITextView

3 Solutions Collect From Internet About “Applying a Word Limit to a UITextView”

You can just count the number of spaces and restrict that. It’s a hack, but it works.

You can do this inside

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText

by using one of these NSString methods

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

For example, you can do something along these lines:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText {
        NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];
        NSString *trimmedText = [newText stringByReplacingOccurrencesOfString:@" " withString:@""];

        if (newText.length - trimmedText.length > wordLimit) {
            return NO;
        } else {
            return YES;
        }
}

If you want to be more accurate, you can also “fix” the text first by replacing multiple spaces with a single space and inserting a space after punctuation. This should probably be written as a separate function that you call on the input text.

If you’re using iOS 4.0 or later, you might be able to get better results using NSRegularExpression. I haven’t tried this out, but something like the following should be close:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\w+"
                                                                       options:0
                                                                         error:&error];
NSUInteger wordCount = [regex numberOfMatchesInString:string
                                              options:0
                                                range:NSMakeRange(0, [string length])];

Another idea besides counting the spaces is to use the average word length of 5 characters + 1 space to determine the number of words. In other words, take your total character count divided by 6 to get your estimated word count. It’s a bit faster that way if you’re ok with it not being 100% accurate.