Is it possible to to have more than one color in the same UILabel

梦想与她 提交于 2019-12-23 02:38:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!