rangeOfString
returns the first occurrence, that's normal behavior.
From the Doc:
Finds and returns the range of the first occurrence of a given string within the receiver.
You could use a NSRegularExpression
, and use matchesInString:options:range
to get a NSArray
of NSTextCheckingResult
(that have a NSRange
property), an use a for loop
to bold it.
This should do the trick:
- (void)boldSubstring:(NSString*)substring
{
if (![self respondsToSelector:@selector(setAttributedText:)])
{
return;
}
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: substring options:NSRegularExpressionCaseInsensitive error:&error];
if (!error)
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[self text]];
NSArray *allMatches = [regex matchesInString:[self text] options:0 range:NSMakeRange(0, [[self text] length])];
for (NSTextCheckingResult *aMatch in allMatches)
{
NSRange matchRange = [aMatch range];
[attributedString setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range: matchRange];
}
[self setAttributedText:attributedString];
}
}