【问题标题】:Can I make a button in swift whose text has multiple colors?我可以快速制作一个文本有多种颜色的按钮吗?
【发布时间】: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


【解决方案1】:

你可以用这个:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2015-02-24
    • 2015-01-03
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多