gpt4 book ai didi

ios - 我可以快速制作一个文本有多种颜色的按钮吗?

转载 作者:行者123 更新时间:2023-11-28 09:31:55 25 4
gpt4 key购买 nike

我可以在 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)

关于ios - 我可以快速制作一个文本有多种颜色的按钮吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com