Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide different font color in same label programatically involving dynamic text

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!

like image 459
tech savvy Avatar asked Mar 21 '23 01:03

tech savvy


1 Answers

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

like image 180
Greg Avatar answered Mar 23 '23 15:03

Greg