Adding Text in SwiftUI
Last updated
Last updated
Text
views are one of the most fundamental and frequently used components in any SwiftUI user interface. They enable you to display text in your app, serving as labels, titles, descriptions, and much more. SwiftUI's Text
views are simple to use, require minimal code, and offer a wide range of customization options.
To create a Text
view, you use the Text
initializer and provide the text you want to display. Here's an example:
In the above code, the TextSwiftUI
struct conforms to the View
protocol. Within the body
property, we return a Text
view that displays "Hello, World!".
One of the powerful features of SwiftUI is the ability to customize views using modifiers. Let's explore some of the common modifiers you can use with Text
views.
You can change the font style of your text using the .font()
modifier. Here's how to set the text to a headline style:
To change the color of the text, use the .foregroundColor()
modifier:
To make the text bold or italic, use the .bold()
and .italic()
modifiers:
If you want to use a custom font and size, you can do so with the .font()
modifier combined with .custom()
:
Adjusting the line spacing and text alignment can enhance readability:
Adding a shadow to your text can create a more dramatic effect:
You can apply strikethrough or underline to your text:
Modifiers can be chained to apply multiple customizations: