1

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?

mad_manny
  • 1,081
  • 16
  • 28
gran_profaci
  • 8,087
  • 15
  • 66
  • 99

3 Answers3

1

rangeOfString Returns only one range not all the range. Loop and set all the ranges

NSRange range = [event1 rangeOfString:@"*"];

while (range.length > 0)
{
    [att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]];
     //check for the presence of * in the rest of the string
    range = [[event1 substringFromIndex:(range.location + range.length)] rangeOfString:@"*"];
}
nprd
  • 1,942
  • 1
  • 13
  • 16
1

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];
picciano
  • 22,341
  • 9
  • 69
  • 82
0

You need to find each time the "*" character is encountered in your string.

And to do that, you can use a routine like the one found in this related question.

The only thing you'd need to remove this line from the code:

[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)];

and replace it with your code:

 [mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];
Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215