Say I have NSString * hello = @”hello world”;
Now I want an atributed string where the hell in hello world is bolded.
There is a function on the web that do this:
- (NSMutableAttributedString*) word:(NSString*)substringToHighlight{
NSMutableAttributedString * mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:self];
NSUInteger count = 0, length = [mutableAttributedString length];
NSRange range = NSMakeRange(0, length);
count = 0,
length = [mutableAttributedString length];
range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[mutableAttributedString string] rangeOfString:substringToHighlight options:0 range:range];
if(range.location != NSNotFound) {
//[mutableAttributedString setTextColor:[UIColor blueColor] range:NSMakeRange(range.location, [word length])];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return mutableAttributedString;
}
However, the function doesn’t work because mutableAttributedString doestn’t support setTextColor
I also tried
NSDictionary * dict = @{kCTFontAttributeName:boldFontName};
[mutableAttributedString setAttributes:{kCTFontAttributeName:boldFontName} range:NSMakeRange(range.location, substringToHighlight.length)];
but got a message kCTFontAttributeName is not defined.
You can use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway).
Finds and returns the range of the first occurrence of a given string, within the given range of the receiver, subject to given options.
(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRangeThis is another solution :
Then you need to convert into
NSMutableAttributedStringlike this way.I think this is the best solution.