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.
The font-weight CSS property sets the weight (or boldness) of the font.
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
What is Markdown?
Use double asterisks (**) arroud the characters that you want to make bold.
Text("**CO**rona**V**irus **D**isease of 20**19**")
Use underscore (_) arround the charachters you want to make italic.
Text("Is this text _emphasized_?")
Use init(_ value: String)
Creates a localized string key from the given string value.
let bold = "This text is **bold**"
Text(.init(bold))
Use init(_ value: String)
Creates a localized string key from the given string value.
let bold = "Bold"
Text(.init("This text is **\(bold)**"))
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
If you don't need to translate it here is possible fast variant
Text("CO").bold() + Text("rona") + Text("VI").bold() +
Text("rus Disease of 20") + Text("19").bold()
alternate is to use NSAttributedString with UIViewRepresentable
of UILabel
.
A quick note just to add onto Asperi's great answer, if you need to apply frame or padding modifiers to your text you'll need to group the text first and then add your modifiers to the group.
Group { Text("CO").bold() + Text("rona") + Text("VI").bold() + Text("rus Disease of 20") + Text("19").bold() }.frame(width: 100, height: 100).padding(.horizontal)
Flavours of this question crop up a lot and for a newcomer to Swift without a background in Objective-C, the solutions emerge grudgingly. Several of the above answers are excellent, but to summarize perhaps the optimal solution to the question as asked,
Group {
Text("CO").bold() +
Text("rona") +
Text("V").bold() +
Text("irus ") +
Text("D").bold() +
Text("isease of 20") +
Text("19").bold()
}
.font(.caption)
.frame(width: 300)
(Group{}
was the secret sauce for me)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With