Search code examples
swiftswiftui

Making parts of text bold in SwiftUI


I was wondering how I would make only sections of a text bold while keep the rest 'regular' in SwiftUI.

I currently have:

Text("Coronavirus Disease of 2019")

and I want it to print out COronaVirus Disease of 2019 and haven't been able to get only some parts bold.


Solution

  • iOS 15+ (Swift 5.5 +)

    SwiftUI has built-in support for rendering Markdown.

    It is GitHub flavored markdown. AttributedString converts both inline and block styles. SwiftUI renders inline styles (but not images at this time). We use the fantastic cmark-gfm library to parse the markdown string. - SwiftUI Frameworks Engineer - developer.apple.com

    See more:

    What is Markdown?


    Use double asterisks (**) around the characters that you want to make bold.

    Text("**CO**rona**V**irus **D**isease of 20**19**")
    

    Use underscore (_) around the characters you want to make italic.

    Text("Is this text _emphasized_?")
    

    String variable

    Use init(_ value: String)

    Creates a localized string key from the given string value.

    let bold = "This text is **bold**"
    Text(.init(bold))
    

    String interpolation

    Use init(_ value: String)

    Creates a localized string key from the given string value.

    let bold = "Bold"
    Text(.init("This text is **\(bold)**"))
    

    Attributed String

    Use init(_ attributedContent: AttributedString)

    Creates a text view that displays styled attributed content.

    let markdownText = try! AttributedString(markdown: "This text is **bold**")
    Text(markdownText)
    

    See also:

    init(_ attributedContent: AttributedString) - https://developer.apple.com