Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Put a color to only one word in a sentence with localization

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

like image 715
Skylek Avatar asked Sep 28 '20 14:09

Skylek


1 Answers

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 %@.";
like image 61
Pavel Zak Avatar answered Sep 20 '22 13:09

Pavel Zak