在单个标签中使用多种字体颜色 [英] Use multiple font colors in a single label

查看:147
本文介绍了在单个标签中使用多种字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在iOS中的单个标签中使用两种甚至三种字体颜色?

Is there a way to use two, or even three font colors in a single label in iOS?

如果使用你好,你好吗这样的文字作为例子,你好将是蓝色,你好吗将是绿色?

If the text "hello, how are you" were used as an example, the "hello," would be blue, and the "how are you" would be green?

这可能,比创建多个标签更容易吗?

Is this possible, it seems easier than creating multiple labels?

推荐答案

首先初始化你 NSString NSMutableAttributedString ,如下所示。

First of all initialize of you NSString and NSMutableAttributedString as below.

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

ViewDidLoad

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

**您的输出:**

**Your OUTPUT: **

多种颜色

在ViewDidLoad中添加以下行代码以获取字符串中的多种颜色。

Add the line code below in your ViewDidLoad to get multiple colors in a string.

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

多种颜色输出

这篇关于在单个标签中使用多种字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆