For example I have to put a String "Hello, world!" in the UIButton
.
And "Hello," and "world!" should be different colors.
"Hello," has the default color of UIButton
, and "world!" has the customized color by NSMutableAttributedString
.
I explain again with code and result.
// Using a library `SwiftyAttributes`(https://github.com/eddiekaiger/SwiftyAttributes)
button.attributedText = "Hello, ".withJust() + "world!".withTextColor(.red)
button.setTitleColor(.black, for: .normal)
I want: Hello,(black) world!(red)
button.setTitleColor(.red, for: .normal)
I want: Hello,(red) world!(red)
button.setTitleColor(.blue, for: .normal)
I want: Hello,(blue) world!(red)
But always the result is: Hello,(black) world!(red)
...
Maybe I think the priority of NSMutableAttributedString
default color is higher than UIButton
default color.
But can I see the result I want?
You seem to imagine there is some kind of "inheritance" between the title color and the color in the attributed string. There isn't. There is no relationship between them at all.
As soon as you start using
attributedText
, you are completely in charge of the colors in the text. The tint color and title color become completely irrelevant. If you want Hello in blue you must set it to blue in the attributed string.