-3

I want to know how to change the colour of substring within a string. So for example, I have the following original black colour substring:

NSString *original=@"Frank Megan Timmy
                    Marcus Andrea Matt
                   Jamie Lauren Marcus";

Let us assume that the user has done something and I would like to make Marcus Andrea Matt a RED colour (for example) within the original string and keep everything else the same.

Can anyone tell me how this can do be done?

Sebastian
  • 7,670
  • 5
  • 38
  • 50
Teddy13
  • 3,824
  • 11
  • 42
  • 69

3 Answers3

1
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"Frank Megan Timmy Marcus Andrea Matt Jamie Lauren Marcus"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0,18)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(18,18)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(36,20)];

UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 80)];
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setNumberOfLines:0];
[label setAttributedText:string];

[self.view addSubview:label];
Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
0

Use NSMutableAttributedString to do this. Change the type of original to NSMutableAttributedString and use

[original addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:yourRange];
Roshan
  • 1,937
  • 1
  • 13
  • 25
0

Please find below solution:

NSString *original=@"Frank Megan Timmy
                    Marcus Andrea Matt
                   Jamie Lauren Marcus";
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:original];
/ now we only change the color of "Frank"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
manujmv
  • 6,450
  • 1
  • 22
  • 35