How to make parts of Text view Bold in SwiftUI
Table of Contents
There are two easy ways to style parts of SwiftUI Text view.
- Using Markdown (iOS 15)
- Text Concatenation
Here is an example where we make the word "World!" bold.
Markdown
In iOS 15, we can initialize a Text view using a markdown string. So, we can easily make parts of a Text view bold by wrapping part of the string with double asterisks (**
) or double underscore (__
).
Text("Hello, **World!**")
.font(.largeTitle)
Text("Hello, __World!__")
.font(.largeTitle)
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
Text Concatenation
If you support iOS before iOS 15, you need to use the +
operator.
Text
view provide +
operator which concatenates multiple text views into a new text view.
You can combine text views with multiple styles into one using this operator. Here is an example of creating a "Hello, World!" text view using the +
operator.
struct ContentView: View {
var body: some View {
Text("Hello, ")
.font(.largeTitle) +
Text("World!")
.bold()
.font(.largeTitle)
}
}
We bold the second text with the .bold()
modifier and append it to the first one with +
.
This operator is very flexible. You can combine as many text views as you want. And you can apply any text modifiers as long as the modifier returns a text view.
Here is another example using this technique.
struct ConcatTextExample: View {
var body: some View {
VStack {
Text("Tempore ") +
Text("distinctio ").bold() +
Text("molestiae ").italic() +
Text("corporis ").foregroundColor(.pink) +
Text("sapiente ").foregroundColor(.orange) +
Text("natus ").foregroundColor(.yellow) +
Text("sunt quo.")
}
.font(.largeTitle)
}
}
We combine multiple texts with multiple modifiers in this example.
Read more article about Swift, Text, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to fix preferredStatusBarStyle not getting called
Two common reasons make the preferredStatusBarStyle not getting called.