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

1

9

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

Rohr answered 28/9, 2020 at 14:19 Comment(3)
Does this answer your question https://mcmap.net/q/1013929/-exceeding-max-text-quot-quot-concatenation-length-swiftui?Dobbs
Thanks, it's perfect !Rohr
Does this answer your question? Exceeding max Text("") concatenation length - SwiftUI -Undulant
J
14

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 %@.";
Jurisconsult answered 29/9, 2020 at 13:49 Comment(2)
Does that support ordering of two arguments as well?Naturalize
Yes it does ;) In one language, you can have "MyLocalizedKey %@" = "My name is %@."; while in other "MyLocalizedKey %@" = "%@ is my name"Jurisconsult

© 2022 - 2024 — McMap. All rights reserved.