我可以快速制作一个文本有多种颜色的按钮吗? [英] Can I make a button in swift whose text has multiple colors?

查看:36
本文介绍了我可以快速制作一个文本有多种颜色的按钮吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以快速制作一个文本有多种颜色的按钮吗?按钮文字会动态变化,所以我无法制作它的图像.

Can I make a button in swift whose text has multiple colors? The button text will change dynamically, so I cannot make an image of it.

我尝试制作两个不同颜色的属性字符串,将它们连接起来,然后将按钮的文本设置为那个.不幸的是,这并没有保留不同的颜色,只是在字符串的末尾添加了描述 nsattributes 的明文.

I have tried to make two attributed strings with different colors, concatenate them, and set the button's text to that. Unfortunately, that does not preserve the different colors and just adds plaintext describing the nsattribtues at the end of the string.

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 行我尝试设置标题.与上述相同的问题仍然存在.

I want the currDescString to be black and the editString to be blue...In line 3 i try to concatenate those and in line 4 I try to set the title. Same problem as stated above persists.

推荐答案

你可以使用这个:

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 参数来指定子字符串应具有的颜色.

You can use the range parameter of addAttribute method to specify which color that substring should have.

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

And for your example this is something like this:

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)

这篇关于我可以快速制作一个文本有多种颜色的按钮吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆