richc
richc

Reputation: 1678

How to set the UIColor for each letter in a string

Is there a simple way to set the colour for each letter in a UILabel in swift? (Or any other text for that matter!)

For example

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

But I want the S to be red, the p to be blue, the e to be yellow etc.

Thanks in advance if anyone knows how to do this easily...

I got this to work with help from those below. And added the attributed string to a UIButton title.

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)]

Upvotes: 0

Views: 80

Answers (1)

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

For creating of the colorful string you should use NSMutableAttributedString.

Small example:

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

Upvotes: 3

Related Questions