I need to highlight words in my UITextView
one by one. How do I get the NSRange values of all the words of a UITextView
and store them in an NSArray
?
You can use this method of NSString
- enumerateSubstringsInRange:options:usingBlock:, and use NSStringEnumerationByWords
for option. It will iterate over all words of your string and give you the range of it, that you can save into an array.
NSString *string = @"How do I get the NSRange values of all the words of a UITextView in an array";
NSMutableArray *words = [NSMutableArray array];
NSMutableArray *ranges = [NSMutableArray array];
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByWords
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[words addObject:substring];
[ranges addObject:[NSValue valueWithRange:substringRange]];
}
];
NSLog(@"Words:\n%@", words);
NSLog(@"Ranges:\n%@", ranges);