Suppose you want to change the some text of your label 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.Firstly, you have to find the the range of text,which you want to change the color of that text and then set the range of your text to the NSMutableAttributedString object as compared to full string and then set your label attributedText with the NSMutableAttributedString object.Example :-
1 2 3 4 5 |
let strNumber: NSString = "Hello Test" as NSString // you must set your let range = (strNumber).range(of: "Test") let attribute = NSMutableAttributedString.init(string: strNumber) attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range) yourLabel.attributedText = attribute |
If you want to use this in many times in your application you can just create the extension of the UILabel and it will make more simple :-
1 2 3 4 5 6 7 8 9 |
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(NSForegroundColorAttributeName, value: UIColor.red , range: range) self.attributedText = attribute } } |
Use your label:-
1 2 |
yourLabel = "Hello Test" yourLabel.halfTextColorChange(fullText: totalLabel.text!, changeText: "Test") |
Be the first to comment.