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

北慕城南 提交于 2019-12-12 03:50:22

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/38594885/can-i-make-a-button-in-swift-whose-text-has-multiple-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!