问题
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:
回答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];
来源:https://stackoverflow.com/questions/10789518/is-it-possible-to-to-have-more-than-one-color-in-the-same-uilabel