SwiftUI 使用本地化为句子中的一个单词添加颜色

Sky*_*lek 4 string localization swift swiftui

我想为放置在 Text() 中的字符串的一个单词添加颜色。这个词可以根据定位放置在字符串中的不同位置。


例子:

MYAPP是我想放红色的词)

中文: 您好,欢迎使用MYAPP应用程序。

法语: Bonjour, bienvenue dans l'application MYAPP


在我的代码中,我可以使用:

Text("Hello, welcome in ") 
+ Text("MYAPP").foregroundColor(.red)
+ Text("app")
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为如果我用法语使用该应用程序,“应用程序”一词将不会放在句尾,而是放在 MYAPP之前, 所以我无法将它与本地化一起使用,我需要这样做

我试过这样的东西,我在网上找到的:

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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?谢谢

Pav*_*Zak 5

您可以使用新的字符串插值功能:

struct ContentView: View {
var body: some View {
    HStack {
        Text("MyLocalizedKey \(Text("Red word").foregroundColor(Color.red))")
    }
}
Run Code Online (Sandbox Code Playgroud)

}

在您的 Localizable.strings 中,您将拥有:

"MyLocalizedKey %@" = "My name is %@.";
Run Code Online (Sandbox Code Playgroud)