代码之家  ›  专栏  ›  技术社区  ›  Milly Alfaro

删除修改文本中的空白

  •  1
  • Milly Alfaro  · 技术社区  · 3 年前

    我有一个函数,可以接收文本并检查@符号。输出是相同的文本,但@符号后面的任何单词都将被着色,类似于社交媒体提及的内容。问题是,它在原文的前面增加了一个额外的空白。如何修改输出以删除它添加到新文本前面的空白?

    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 @stackoverflow how is it going?", color: .red)
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   workingdog support Ukraine    3 年前

    试试这样:

    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
        }