3

I'm trying to show my response data using SwiftUI Text with formatted text ex: Bold, but for some reason it's not working 🤔

The needed behaviour as below:

enter image description here

This is working!

Text("**Hello** *World*")

But this is not 🤔

let text: String = "**Hello** *World*"
Text(text)

Am I missing something 🤔

2

1 Answer 1

21

After test and fail moments, I found that Text only handles markdown when string literal is passed to initializer. as below:

to achieve the needed behavior:

let text: String = "**Hello** *World*"
    
Text("**Hello** *World*") // will be rendered with markdown formatting
Text(text) // will NOT be rendered according to markdown
Text(.init(text)) // will be rendered with markdown formatting

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Early 2024, answer still helpful; thank you!
I feel like I always can't quite get this to work, and I set up my strings just right, and it still doesn't work, so I pull up this answer, and go back to me code, and without touching a thing, the text is magically formatted correctly. Best swift answer on SO. Magical.
This answer no longer works. The correct approach is to use LocalizedStringKey so SwiftUI interprets the string as Markdown: The correct way is use LocalizedStringKey: struct ContentView: View { let markdownText: LocalizedStringKey = "Hello World" var body: some View { Text(markdownText) } } Using LocalizedStringKey tells Text to treat the value as localized Markdown, so the bold and italic formatting are rendered.
I'm on macOS 26.1 building for iOS 26.1 and it still works...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.