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.
Implementation
To Implementation of this you need to follow below mention steps.
You may also check our Flutter App development services.
1. Create New Projects:
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.
2. Create UILabel:
After that you need to add UILabel either programatically or using Storyboard.
1 |
@IBOutlet weak var label: UILabel! |
3. Change UILabel Color:
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.
4. Create Extension:
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.
5. Use Extension To Change Some Text Color Of UILabel:
1 |
label.halfTextColorChange(fullText: label.text!, changeText: "Hello") |
Above code in helpful to change some text color of UILabel using extension.
Output
Conclusion
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.