1

I have this function which when called in a view will, take the inputted String, and output the same string, but with words following the @ symbol changed in colour:

func textWithSymbols(_ text: String, color: Color) -> Text {
        let words = text.split(separator: " ")
        var output: Text = Text("")

        for word in words {
            if word.hasPrefix("@") { // Pick out @ in words
                output = output + Text(" ") + Text(String(word))
                    .foregroundColor(color) // Add custom styling here
            } else {
                output = output + Text(" ") + Text(String(word))
            }
        }
        return output
    }

I would call it like:

var txt = "What do you think @test"

textWithSymbols(txt, color: .red)

The result would be the same text, but @test would be highlighted in red.

How would I apply this same functionality to both a text field and text editor where text is constantly being updated?

I've used the .onChange modifier before for stuff like counting lines and replacing text, so maybe that might be a start?

Milly Alfaro
  • 299
  • 3
  • 15
  • You're looking for something akin to Attributed Text. Implementing this in SwiftUI will require the use of UIViewRepresentable however, so be prepared for that. This might also be useful. https://stackoverflow.com/questions/62111551/highlight-a-specific-part-of-the-text-in-swiftui – xTwisteDx Apr 13 '22 at 17:26

0 Answers0