#hashtag Styling in SwiftUI
Quick Tip Tutorial

#hashtag Styling in SwiftUI

Jean-Marc Boullianne
Jean-Marc Boullianne

Using the function below you can easily create a Text view in SwiftUI with custom formatting for the hashtags contained in the text.

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
}

Example Use

SwiftUI Text with hashtag formatting
struct ContentView: View {
    var body: some View {
        textWithHashtags("Here's a quick and easy way to include #hashtag formatting in your #SwiftUI Text Views. Learn how in the #Tutorial here.", color: .red)
            .font(Font.custom("Avenir Next", size: 20))
            .bold()
            
    }
}