SwiftUI:如何在本地化字符串中仅给一个单词上色

9

我想在Text()中的一个单词上设置颜色。 根据语言环境,该单词可能位于字符串中的不同位置。


示例:

MYAPP 是我想要以红色显示的单词)

英语中: Hello,欢迎使用MYAPP应用程序。

法语中: Bonjour,欢迎使用MYAPP应用程序。


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

Text("Hello, welcome in ") 
+ Text("MYAPP").foregroundColor(.red)
+ Text("app")

但这不起作用,因为如果我在使用法语的应用程序时,单词'app'不会放在句子的末尾而是在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

任何建议? 谢谢。

1
这个回答解决了你的问题吗?https://dev59.com/jbzpa4cB1Zd3GeqPHUOw#62976651 - Asperi
谢谢,非常完美! - Skylek
这个回答解决了你的问题吗?超出最大Text("")串联长度-SwiftUI- - JeffUK
1个回答

14
您可以使用新的字符串插值功能:
struct ContentView: View {
var body: some View {
    HStack {
        Text("MyLocalizedKey \(Text("Red word").foregroundColor(Color.red))")
    }
}

而在你的Localizable.strings文件中,你应该有:

"MyLocalizedKey %@" = "My name is %@.";

那是否也支持对两个参数进行排序? - gnasher729
是的,它可以;在一种语言中,你可以有"MyLocalizedKey %@" = "My name is %@。";而在另一种语言中,"MyLocalizedKey %@" = "%@ is my name"。 - Pavel Zak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接