【发布时间】: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
有什么想法吗? 谢谢
【问题讨论】:
-
这是否回答了您的问题stackoverflow.com/a/62976651/12299030?
-
谢谢,太完美了!
标签: swift string localization swiftui