我可以在 swift 中制作一个文本有多种颜色的按钮吗?
Can I make a button in swift whose text has multiple colors?
我可以在 swift 中制作一个文本有多种颜色的按钮吗?按钮文本会动态变化,所以我无法制作它的图像。
我尝试制作两个具有不同颜色的属性字符串,将它们连接起来,然后将按钮的文本设置为该颜色。不幸的是,这并没有保留不同的颜色,只是在字符串末尾添加了描述 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 行中,我尝试设置标题。与上述相同的问题仍然存在。
你可以使用这个:
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 方法的范围参数来指定子字符串应该具有的颜色。
对于您的示例,它是这样的:
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)
我可以在 swift 中制作一个文本有多种颜色的按钮吗?按钮文本会动态变化,所以我无法制作它的图像。
我尝试制作两个具有不同颜色的属性字符串,将它们连接起来,然后将按钮的文本设置为该颜色。不幸的是,这并没有保留不同的颜色,只是在字符串末尾添加了描述 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 行中,我尝试设置标题。与上述相同的问题仍然存在。
你可以使用这个:
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 方法的范围参数来指定子字符串应该具有的颜色。
对于您的示例,它是这样的:
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)