iphone - 如何在同一标签上使用不同颜色

标签 iphone objective-c uilabel

我要写的问题已经使用两个UILabel解决了。我正在寻找一些优化方法。 我有一个字符串 (示例:hello world ) 需要在具有不同颜色的 UILabel 中显示。例如 “红色的 hello ”和“绿色的世界”颜色”

提前致谢

最佳答案

假设您有一个名为 ColoredLabel 的文本标签,并且您想用红色写“hello”,用绿色写“world”。
从 iOS 6 开始,您可以创建属性字符串并将其设置为标签的属性文本:

    NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: @"Hello world"];
    [str setAttributes: @{ NSForegroundColorAttributeName : [UIColor redColor] }  range: NSMakeRange(0, 5) ];
    [str setAttributes: @{ NSForegroundColorAttributeName : [UIColor greenColor] }  range: NSMakeRange(6, 5) ];
    coloredLabel.attributedText= str;

关于iphone - 如何在同一标签上使用不同颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452662/

相关文章:

ios - 以编程方式创建 UILabel 并设置其位置

ios - 让我们缩短 cell.textLabel 的长度

iphone - UIWebView 周围的透明度

ios - 在我的应用程序中支持 iPad 和 iPhone 的最佳方法是什么?

iphone - 如何在 iOS 上使用 AES、CCrypt 加密/解密大文件的 block / block ?

ios - 在现有 ARC 项目中实现 OCUnit 的问题

iphone - 使用标签/UILabels/UIViews

iphone - dequeueReusableCellWithIdentifier、自定义 UITableViewCell 的问题

objective-c - 准备不使用 swift 的 segue

iphone - EventKit 框架中的贪睡方法?