Reputation: 12517
How is it possible to apply a word limit to a UITextView in objective-c/interface builder.?
I have been searching for a while and have found character count but not word count...
Cany anybody give me any pointers...
Upvotes: 3
Views: 2442
Reputation: 8292
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])];
Upvotes: 2
Reputation: 48398
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.
Upvotes: 6
Reputation: 22266
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.
Upvotes: 0