Swift 属性文本的颜色如何继承父颜色?

Swift 属性文本的颜色如何继承父颜色?,swift,string,nsmutableattributedstring,Swift,String,Nsmutableattributedstring,例如,我必须在ui按钮中输入一个字符串“Hello,world!” “你好”和“世界!”应该是不同的颜色 “Hello”的默认颜色为UIButton,“world!”的自定义颜色为nsmutableAttributeString 我用代码和结果再次解释 // Using a library `SwiftyAttributes`(https://github.com/eddiekaiger/SwiftyAttributes) button.attributedText = "Hello, ".wi

例如,我必须在
ui按钮中输入一个字符串“Hello,world!”

“你好”和“世界!”应该是不同的颜色

“Hello”的默认颜色为
UIButton
,“world!”的自定义颜色为
nsmutableAttributeString

我用代码和结果再次解释

// Using a library `SwiftyAttributes`(https://github.com/eddiekaiger/SwiftyAttributes)
button.attributedText = "Hello, ".withJust() + "world!".withTextColor(.red)

button.setTitleColor(.black, for: .normal)
我要:你好,(黑色)世界!(红色)

我要:你好,(红色)世界!(红色)

我要:你好,(蓝色)世界!(红色)

但结果总是:你好,(黑色)世界!(红色)

也许我认为
nsmutableAttributeString
默认颜色的优先级高于
UIButton
默认颜色


但是我可以看到我想要的结果吗?

您似乎想象在标题颜色和属性字符串中的颜色之间存在某种“继承”。没有。他们之间根本没有关系


一旦开始使用
attributedText
,您就完全掌握了文本中的颜色。色调颜色和标题颜色变得完全不相关。如果希望Hello显示为蓝色,则必须在属性字符串中将其设置为蓝色。

为此,您确实应该使用
NSMutableAttributedString
,但您应该建立
NSMutableAttributedString
,而不是像以前那样。以下是一些代码供您开始使用:

let attrStr = NSMutableAttributedString(string: "Hello World")
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location: 0, length: 5))
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 6, length: 5))
button.setAttributedTitle(attrStr, for: .normal)
请注意,
位置
是要开始着色的位置,
长度
是要停止着色的位置。所以
Hello
变成
location:0
length:5

输出:

button.setTitleColor(.blue, for: .normal)
let attrStr = NSMutableAttributedString(string: "Hello World")
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location: 0, length: 5))
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 6, length: 5))
button.setAttributedTitle(attrStr, for: .normal)