4

Hi Below is the kind of view I need to achieve using UILabel. I have heard about NSAttributedString but not sure how to use it for dynamic text loading.

enter image description here

Here the whole text font is Roboto-Light. However, I have to replace text 'Dr Andrew Murphy, John Smith' from the API response for first two doctors and get the count for '23 doctors' from API so that it adjusts in this label accordingly. Text color as you can see depends upon if text is constant or dynamic. I am not sure how to achieve it. Hence some code snippets are really welcome.

Thanks!

n00bProgrammer
  • 4,261
  • 3
  • 32
  • 60
tech savvy
  • 1,417
  • 4
  • 21
  • 42
  • 1
    Please see this post and it's answer as I think it has exactly what you're looking for. http://stackoverflow.com/questions/3482346/how-do-you-use-nsattributedstring – Milo Jan 09 '14 at 15:33

2 Answers2

5

You can use NSMutableAttributeString with addAttribute:value:range like that;

//Your entry string
NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' ";
//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];

//Fing range of the string you want to change colour
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:@"John Smith"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];

//Add it to the label - notice its not text property but it's attributeText
label.attributedText = attString;

Hope this help

Greg
  • 25,317
  • 6
  • 53
  • 62
  • One more thing if to this attributed string I need to add Roboto-Light font with size 13. What function do I use? – tech savvy Jan 10 '14 at 07:22
  • got it by following code: UIFont *font=[UIFont fontWithName:@"Roboto-Light" size:13.0f]; [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [myString length])]; – tech savvy Jan 10 '14 at 07:37
2

Create an NSMutableAttributedString with the raw text.

Then find the range of a string you wish to color. Use that range with the NSMutableAttributedString setAttributes:range: method.

Repeat for each bit of text you wish to color.

rmaddy
  • 314,917
  • 42
  • 532
  • 579