【发布时间】:2016-07-26 16:08:37
【问题描述】:
我可以快速制作一个文本有多种颜色的按钮吗?按钮文本会动态变化,所以我无法制作它的图像。
我尝试制作两个具有不同颜色的属性字符串,将它们连接起来,然后将按钮的文本设置为该字符串。不幸的是,这不会保留不同的颜色,只是在字符串末尾添加描述 nsattribtues 的纯文本。
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 行我尝试设置标题。与上述相同的问题仍然存在。
【问题讨论】:
-
您只需要一个
NSAttributedString,将一个范围设置为一种颜色,将另一个范围设置为另一种颜色。然后使用setAttributedTitle:forState:将其设置为按钮的标题。 -
您能否展示您尝试使用属性字符串的代码?它应该保留颜色。你可能错过了什么。
-
我在上面的原始问题中添加了代码和更多信息...如果它有助于您的分析,请告诉我
-
您的问题与
editDescriptionString的构造有关。这很正常,它没有工作。您使用字符串创建它,而不是之前的属性字符串(包含颜色和其他渲染效果)。您应该附加它们。
标签: ios swift uibutton nsattributedstring