I want to put a color to one word of a string placed in a Text(). This word can be placed in different position in the string depending on the localization.
Examples:
(MYAPP is the word I want to put in red color)
In english: Hello, welcome in MYAPP app.
In french: Bonjour, bienvenue dans l'application MYAPP.
In my code, I could have used:
Text("Hello, welcome in ")
+ Text("MYAPP").foregroundColor(.red)
+ Text("app")
But this is not working because if I use the app in french, the word 'app' will not be placed at the end of the sentence but before MYAPP So I can't use it with localization and I need to.
I've tried stuff like this that i found on the net:
let color = UIColor.red;
let textToFind = "redword"
let attrsString = NSMutableAttributedString(string:yourlabel.text!);
// search for word occurrence
let range = (yourlabel.text! as NSString).range(of: textToFind)
if (range.length > 0) {
attrsString.addAttribute(NSForegroundColorAttributeName,value:color,range:range)
}
// set attributed text
yourlabel.attributedText = attrsString
Any ideas ? Thanks