Adding Text in SwiftUI
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.
Creating a Basic Text View
To create a Text view, you use the Text initializer and provide the text you want to display. Here's an example:
import SwiftUI
struct TextSwiftUI: View {
var body: some View {
Text("Hello, World!")
}
}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!".
Customizing Text Views with Modifiers
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.
Font Style
You can change the font style of your text using the .font() modifier. Here's how to set the text to a headline style:
Text Color
To change the color of the text, use the .foregroundColor() modifier:
Bold and Italic Text
To make the text bold or italic, use the .bold() and .italic() modifiers:
Custom Font and Size
If you want to use a custom font and size, you can do so with the .font() modifier combined with .custom():
Line Spacing and Alignment
Adjusting the line spacing and text alignment can enhance readability:
Advanced Customizations
Shadow
Adding a shadow to your text can create a more dramatic effect:
Strikethrough and Underline
You can apply strikethrough or underline to your text:
Applying Multiple Modifiers
Modifiers can be chained to apply multiple customizations:
Screenshots

Last updated
Was this helpful?