1

I want more than one font color in the same UILabel. I dont know if it is possible. I dont really think so but maybe some of you out there have a smart solution for it? Maybe something like stringWithFormat. [NSString stringWithFormatAndColor: @"Text with color: %@ %@", text, color, text, color]

This image illustrate what I'm trying to accomplish:

enter image description here

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
picknick
  • 3,897
  • 6
  • 33
  • 48
  • 1
    possible duplicate of http://stackoverflow.com/questions/3952571/uilabel-with-two-different-color-text – Adam May 28 '12 at 19:26

1 Answers1

1

You can achieve this with NSAttributedSting. An easy to use drop-in replacement for UILabels with support for attributed strings is TTTAtributedLabel or OHAttributedLabel

In my experience it is easier to work with NSMutableAttributedStrings and build it up step by step.

NSMutableAttributedString *attrStr = [NSMutableAttributedString attributedStringWithString:@""];

NSMutableAttributedString *a = [NSMutableAttributedString attributedStringWithString:@"This is "];      
[a setTextColor:aColorObj];
NSMutableAttributedString *b = [NSMutableAttributedString attributedStringWithString:@"only one "];     
[b setTextColor:bColorObj];
NSMutableAttributedString *c = [NSMutableAttributedString attributedStringWithString:@"Label"];     
[c setTextColor:cColorObj];

[attrStr appendAttributedString:a];
[attrStr appendAttributedString:b];
[attrStr appendAttributedString:c];


OHAttributedLabel *attributedTextLabel = [[OHAttributedLabel] initWithFrame:frame]
[attributedTextLabel setAttributedText:attrStr];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • 1
    Note that Viking's solution will only work for Mac OS. iOS doesn't support mixed text styles in UIKit objects. You have to either use a web view or drop down to Core Text to display multiple styles in the same string. You can also fake it by putting separate labels next to each other. – Duncan C May 29 '12 at 02:30
  • I tried the code above and it does work. @DuncanC did you take into account that we are using a OHAttributedLabel and not a UILabel? – picknick May 29 '12 at 07:13