我有一个函数,可以接收文本并检查@符号。输出是相同的文本,但@符号后面的任何单词都将被着色,类似于社交媒体提及的内容。问题是,它在原文的前面增加了一个额外的空白。如何修改输出以删除它添加到新文本前面的空白?
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
for word in words {
if word.hasPrefix("@") {
output = output + Text(" ") + Text(String(word))
.foregroundColor(color)
} else {
output = output + Text(" ") + Text(String(word))
}
}
return output
}
只需在如下视图中调用函数
textWithHashtags("Hello @stackoverflow how is it going?", color: .red)