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.
(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
You can use the new string interpolation feature:
struct ContentView: View {
var body: some View {
HStack {
Text("MyLocalizedKey \(Text("Red word").foregroundColor(Color.red))")
}
}
}
And in your Localizable.strings you would have:
"MyLocalizedKey %@" = "My name is %@.";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With