2017-09-05 128 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