swift - 如何为字符串中的每个字母设置 UIColor

标签 swift text format uicolor

有没有一种简单的方法可以快速设置 UILabel 中每个字母的颜色? (或与此相关的任何其他文本!)

例如

let label = UILabel(frame CGRectMake(100,100,100,100))
label.text = "spell"
label.textColor = UIColor.whiteColor()

但我希望 S 是红色的,p 是蓝色的,e 是黄色的等等。

如果有人知道如何轻松地做到这一点,请提前致谢...

在下面那些人的帮助下,我得到了这个。并将属性字符串添加到 UIButton 标题。

let mainspring = "spell"
let spellAttrString: NSMutableAttributedString = NSMutableAttributedString(string: mainString)

        spellAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: NSRange(location: 0,length: 1))
        spellAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 1, length: 1))
        spellAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSRange(location: 2, length: 1))
        spellAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 3, length: 1))
        spellAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.magentaColor(), range: NSRange(location: 4, length: 1))

        [spellButton .setAttributedTitle(spellAttrString, forState: .Normal)]

最佳答案

要创建彩色字符串,您应该使用 NSMutableAttributedString

小例子:

var attrString: NSMutableAttributedString = NSMutableAttributedString(string: "Some text")
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 3))

关于swift - 如何为字符串中的每个字母设置 UIColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176946/

相关文章:

css - 使用字体变体 : small caps & text-transform: capitalize 时,Firefox 显示其中带有 x 的框

swift - 当 bool 值为 true 时如何删除该节点?

swift - 写函数式代码时全局函数有什么优势

ios - NEPacketTunnelProvider 嗅探器 iOS

c++ - 内存将由空格分隔的 float 文本文件映射到 float vector

date - SAS 特定日期格式

swift - 无法从 Swift 中的 url 获取网页源

html - 输入类型 "number"不会调整大小

Nginx 日志格式 - 删除变量后面的空格

R 日期格式,如何将日期格式更改为 2011 年 6 月 1 日