MultiColor For Text In Swift
Rainbow in text
Let's have some fun by adding MultiColor for text. So this blog is going to cover how to add multicolor for your UILabel, UITextView, and UIButton
And I created some Extension for it, CodeLink
NSAttributedString
A string that has associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text. So we go with NSAttributedString
UILabel and UITextView
So this is the code for making your Text in multiColor
Let me break the code and explain to you (I know you going to ignore this part, even I do)
myMutableString = NSMutableAttributedString(string: "hello world")
hello world
is label text.
myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location: 5,length: 5))
In
addAttribute
we just givingUIColor
and range you need(To be colored)
yourLabel.attributedText = myMutableString
Now adding attributedText
to label
That's it, same for UITextView
UIButton
everything is the same but at last, we set Attributed Title setAttributedTitle
yourButton.setAttributedTitle(myMutableString, for: .normal)
Extension for MultiColor in text
Same code don't get panic
In your viewController
yourLabel.labelColorChange(For: "Hello World", into: UIColor.red, from: 7, to: 3)
if you need more than Two-color just do recurring method
Example
yourLabel.labelColorChange(For: yourLabel.labelColorChange(For: "Hello World", into: UIColor.green, from: 7, to: 3), into: UIColor.red, from: 7, to: 3)
Hope you got it
Get the code from Github