OOProg
OOProg

Reputation: 189

Can I make a button in swift whose text has multiple colors?

Can I make a button in swift whose text has multiple colors? The button text will change dynamically, so I cannot make an image of it.

I have tried to make two attributed strings with different colors, concatenate them, and set the button's text to that. Unfortunately, that does not preserve the different colors and just adds plaintext describing the nsattribtues at the end of the string.

let currDescString = NSAttributedString(string: descriptor)
let editString = NSAttributedString(string: "(edit)", attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
let editDescriptionString = NSAttributedString(string: "\(descriptor) \(editString)")
subBttn.setAttributedTitle(editDescriptionString, forState: UIControlState.Normal)

I want the currDescString to be black and the editString to be blue...In line 3 i try to concatenate those and in line 4 I try to set the title. Same problem as stated above persists.

Upvotes: 0

Views: 3482

Answers (1)

vbgd
vbgd

Reputation: 1987

You can use this:

let att = NSMutableAttributedString(string: "Hello!");
att.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 0, length: 2))
att.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 2, length: 2))
button.setAttributedTitle(att, forState: .Normal)

You can use the range parameter of addAttribute method to specify which color that substring should have.

And for your example this is something like this:

let string1 = "..."
let string2 = "..."

let att = NSMutableAttributedString(string: "\(string1)\(string2)");
att.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 0, length: string1.characters.count))
att.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: string1.characters.count, length: string2.characters.count))
button.setAttributedTitle(att, forState: .Normal)

Upvotes: 12

Related Questions