2017-09-05 84 views
-2

例如我必须把一个字符串“你好,世界!”在UIButton属性文本的颜色如何继承父级颜色?

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

“你好,”默认颜色为UIButton,“世界!”有由NSMutableAttributedString定制的颜色。

我再次解释代码和结果。

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

button.setTitleColor(.black, for: .normal) 

我想:你好,(黑色)世界(红色)

button.setTitleColor(.red, for: .normal) 

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

button.setTitleColor(.blue, for: .normal) 
我想要:你好,(蓝色)世界!

但始终结果是:你好,(黑色)世界(红色)

...

也许我想的NSMutableAttributedString默认颜色的优先级高于UIButton默认颜色高。

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

回答

0

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

只要你开始使用attributedText,你是完全负责文本的颜色。色调颜色和标题颜色变得完全不相关。如果你想蓝色你好,你必须设置它蓝色在属性字符串

0

你的确应该使用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) 

注意,location是要开始着色和length是要停下来。所以Hello变成location: 0length: 5

输出:
enter image description here