Reputation: 1079
I have multiple UILabels within a Custom Table cell. These labels contain varied text or varied length.
As it stands i have UILabel Subclassed allowing me to implement these methods
- (void)boldRange:(NSRange)range {
if (![self respondsToSelector:@selector(setAttributedText:)]) {
return;
}
NSMutableAttributedString *attributedText;
if (!self.attributedText) {
attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
} else {
attributedText = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
}
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
self.attributedText = attributedText;
NSLog(@"%@", NSStringFromRange(range));
}
- (void)boldSubstring:(NSString*)substring {
NSRange range = [self.text rangeOfString:substring];
[self boldRange:range];
}
This allows me to call [cell.StoryLabel boldSubstring:@"test"];
which will BOLD the first occurrence of the word 'test'.
What i am after is the ability to either create new subclass methods or extend the ones i already have, to allow me to replace ALL occurrences of a specified word within the label.
I have looked into a number of methods including 3rd party frameworks. The trouble i have is this is a learning process for me. I would be far more beneficial for me to try and complete this myself.
Thanks in advance!
Upvotes: 2
Views: 2004
Reputation: 26016
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];
}
}
Upvotes: 4