【问题标题】:SwiftUI Put a color to only one word in a sentence with localizationSwiftUI 为带有本地化的句子中的一个单词添加颜色
【发布时间】:2020-09-28 14:19:33
【问题描述】:

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


示例:

MYAPP是我想用红色表示的词)

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

法语: Bonjour, bienvenue dans l'application MYAPP.


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

Text("Hello, welcome in ") 
+ Text("MYAPP").foregroundColor(.red)
+ Text("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

有什么想法吗? 谢谢

【问题讨论】:

标签: swift string localization swiftui


【解决方案1】:

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

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

}

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

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

【讨论】:

  • 这是否也支持两个参数的排序?
  • 是的 ;) 在一种语言中,您可以使用 "MyLocalizedKey %@" = "My name is %@.";而在其他 "MyLocalizedKey %@" = "%@ is my name"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 2016-07-06
  • 2011-11-05
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多