Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color and font of a string using NSAttributed String

I have a string in which last word would always be of a different color compared to the other words in entire string eg: if the string color is black then last word in the statement would be of red color. I am using NSAttributed string for it as below:

NSDictionary *attrDict = [NSDictionary dictionaryWithObject:[UIFont fontWithName:Arial size:16.0] forKey:NSFontAttributeName];
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:@"This is a" attributes: attrDict];

I would be making similar NSAttributedString for the last word and will the amend it with first string.

Question: I want to add color to the string along with the font. I am already handling the font using dictionary. But can I add the color handler/code in the same dictionary or using "addAttribute:" on NSAttributedString is the only other way to add color or any other attributes?

like image 893
tech_human Avatar asked Oct 11 '13 02:10

tech_human


People also ask

How do I change the color of NSMutableAttributedString?

The main here is to use a NSMutableAttributedString and the selector addAttribute:value:range with the attribute NSForegroundColorAttributeName to change a color of a string range: NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:label.


1 Answers

Add the color to the same dictionary as the font:

NSDictionary *attrDict = @{     NSFontAttributeName : [UIFont fontWithName:Arial size:16.0],     NSForegroundColorAttributeName : [UIColor redColor] }; 
like image 193
rmaddy Avatar answered Sep 30 '22 05:09

rmaddy