有没有一种简单的方法可以快速设置 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/