Search code examples
iosobjective-cnsstringnsmutableattributedstringbulletedlist

How do I bold multiple instances of a character in an NSString?


I have a string like the following :

NSString *a = @"* This is a text String \n * Followed by another text String \n * Followed by a third"

I need to print it as three lines. Now, I wanted the Asterix points in it to be bolded. So I tried :

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a];
[att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]];

But this only bolds the second and third asterix. How do I get them all bold?


Solution

  • As others have mentioned, you need to loop through the string to return multiple ranges. This would work:

    NSString *a = @"* This is a text String \n* Followed by another text String \n* Followed by a third";
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a];
    NSRange foundRange = [a rangeOfString:@"*"];
    
    while (foundRange.location != NSNotFound)
    {
        [att addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20.0f] range:foundRange];
    
        NSRange rangeToSearch;
        rangeToSearch.location = foundRange.location + foundRange.length;
        rangeToSearch.length = a.length - rangeToSearch.location;
        foundRange = [a rangeOfString:@"*" options:0 range:rangeToSearch];
    }
    
    [[self textView] setAttributedText:att];