I am trying to make multiple occurrences in a attributed string bold using something like the following
[attrStr setFont:[UIFont ...] range:[attrStr.string rangeOfString:@"hello world"]];
As you know, 'rangeOfString' always return the FIRST occurrence of the match... I am still quite new to iOS, just wondering what's the best way to set all occurrences to bold... Is there any function provided in NSString or something?
Thanks in advance!
You should first try to get all ranges in the string and then set the attribute for every range. There are some great code examples right here on stackoverflow: https://stackoverflow.com/a/4653266/381870
Edit:
Here's an example for you
- (NSArray *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
NSMutableArray *results = [NSMutableArray array];
NSRange searchRange = NSMakeRange(0, [str length]);
NSRange range;
while ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
[results addObject:[NSValue valueWithRange:range]];
searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
}
return results;
}
Usage:
NSArray *results = [self rangesOfString:@"foo" inString:@"foo bar foo"];
NSLog(@"%@", results);
gives you
(
"NSRange: {0, 3}",
"NSRange: {8, 3}"
)