Ios 我可以用swift制作一个文本有多种颜色的按钮吗?

Ios 我可以用swift制作一个文本有多种颜色的按钮吗?,ios,swift,uibutton,nsattributedstring,Ios,Swift,Uibutton,Nsattributedstring,我可以用swift制作一个文本有多种颜色的按钮吗?按钮文本将动态更改,因此我无法制作它的图像 我尝试用不同的颜色创建两个属性字符串,将它们连接起来,并将按钮的文本设置为该颜色。不幸的是,这并没有保留不同的颜色,只是在字符串的末尾添加了描述NSAttributes的纯文本 let currDescString = NSAttributedString(string: descriptor) let editString = NSAttributedString(string: "(edit)",

我可以用swift制作一个文本有多种颜色的按钮吗?按钮文本将动态更改,因此我无法制作它的图像

我尝试用不同的颜色创建两个属性字符串,将它们连接起来,并将按钮的文本设置为该颜色。不幸的是,这并没有保留不同的颜色,只是在字符串的末尾添加了描述NSAttributes的纯文本

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)

我希望currDescString是黑色的,editString是蓝色的……在第3行中,我尝试连接它们,在第4行中,我尝试设置标题。上述问题仍然存在。

您可以使用以下方法:

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)
可以使用addAttribute方法的range参数指定子字符串应具有的颜色

对于你的例子,这是这样的:

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)

您只需要一个NSAttribute字符串,将一个范围设置为一种颜色,将另一个范围设置为另一种颜色。然后使用setAttributedTitle:forState:将其设置为按钮标题。能否显示您尝试使用属性字符串的代码?它应该保留颜色。您可能遗漏了一些内容。我在上面的原始问题中添加了代码和更多信息…请让我知道这是否有助于您的分析您的问题与editDescriptionString的构造有关。这很正常,它不起作用。您使用字符串创建了它,而不是先前包含颜色和其他渲染效果的attributedString。你应该附加它们。