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

OOP*_*rog 0 uibutton nsattributedstring ios swift

我可以在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)
Run Code Online (Sandbox Code Playgroud)

我希望currDescString为黑色,editString为蓝色...在第3行,我尝试连接这些,在第4行,我尝试设置标题.如上所述的同样问题仍然存在.

vla*_*dan 11

你可以用这个:

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)
Run Code Online (Sandbox Code Playgroud)

您可以使用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)
Run Code Online (Sandbox Code Playgroud)