Updated 19 March 2024
In this article we will learn about how Change Half Or Some Text Color Of UILabel In Swift.
In Swift you can change the color of part of the text in a UILabel by using attributed strings.
Suppose you want the some text color of your UILabel you always create two labels for that but its a wrong approach of changing text color of label. You can use the NSMutableAttributedString for changing the some text color of your label.
To Implementation of this you need to follow below mention steps.
You may also check our Flutter App development services.
First of all we need to create a new project where you want to integrate How to Change Half Or Some Text Color Of UILabel In Swift.
After that you need to add UILabel either programatically or using Storyboard.
1 |
@IBOutlet weak var label: UILabel! |
In this steps we will change UILabel color after adding below mention code.
1 2 3 4 |
let attributeString = NSMutableAttributedString(string: "Hello Moikul") attributeString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red,range:NSRange(location: 0, length: 5) ) label.attributedText = attributeString |
After adding above code you will easily change text color.
If you want to use this in many time in your application then you can just create the extension of the UILabel and it will make more simple.
1 2 3 4 5 6 7 8 |
extension UILabel { func halfTextColorChange (fullText : String , changeText : String ) { let strNumber: NSString = fullText as NSString let range = (strNumber).range(of: changeText) let attribute = NSMutableAttributedString.init(string: fullText); attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range:NSRange(location: 0, length: 7) ) self.attributedText = attribute } } |
Above code is helpful to create a extension of UILabel.
1 |
label.halfTextColorChange(fullText: label.text!, changeText: "Hello") |
Above code in helpful to change some text color of UILabel using extension.
In this article we have discussed about How To Change Half Or Some Text Color Of UILabel In Swift.
Hope this blog is helpful to understand this topic.
For more knowledge please visit here.
Thanks for reading this blog. You can also check other blogs from here for more knowledge.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
1 comments