删除修改后的文本中的空 space
Remove empty space in modified text
我有一个接收文本并检查 @ 符号的函数。输出是相同的文本,但 @ 符号后面的任何单词都会被着色,类似于社交媒体提及。问题是它在原文前面多加了一个空的space。如何修改输出以删除它添加到新文本前面的空 space?
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
for word in words {
if word.hasPrefix("@") { // Pick out hash in words
output = output + Text(" ") + Text(String(word))
.foregroundColor(color) // Add custom styling here
} else {
output = output + Text(" ") + Text(String(word))
}
}
return output
}
只需在像
这样的视图中调用函数
textWithHashtags("Hello @Whosebug how is it going?", color: .red)
尝试这样的事情:
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
var firstWord = true // <-- here
for word in words {
let spacer = Text(firstWord ? "" : " ") // <-- here
if word.hasPrefix("@") { // Pick out hash in words
output = output + spacer + Text(String(word))
.foregroundColor(color) // Add custom styling here
} else {
output = output + spacer + Text(String(word))
}
firstWord = false
}
return output
}
我有一个接收文本并检查 @ 符号的函数。输出是相同的文本,但 @ 符号后面的任何单词都会被着色,类似于社交媒体提及。问题是它在原文前面多加了一个空的space。如何修改输出以删除它添加到新文本前面的空 space?
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
for word in words {
if word.hasPrefix("@") { // Pick out hash in words
output = output + Text(" ") + Text(String(word))
.foregroundColor(color) // Add custom styling here
} else {
output = output + Text(" ") + Text(String(word))
}
}
return output
}
只需在像
这样的视图中调用函数textWithHashtags("Hello @Whosebug how is it going?", color: .red)
尝试这样的事情:
func textWithHashtags(_ text: String, color: Color) -> Text {
let words = text.split(separator: " ")
var output: Text = Text("")
var firstWord = true // <-- here
for word in words {
let spacer = Text(firstWord ? "" : " ") // <-- here
if word.hasPrefix("@") { // Pick out hash in words
output = output + spacer + Text(String(word))
.foregroundColor(color) // Add custom styling here
} else {
output = output + spacer + Text(String(word))
}
firstWord = false
}
return output
}