Introduction
In our last article, we have seen How to add Font and FontWeight in SwiftUI. We covered only these two modifiers for Text view. SwiftUI gives us a variety of view modifiers to allow us to modify the appearance and behavior of the text views in our iOS app. These modifiers can be used to change the font, color, alignment, and other properties of text views. In this article, we'll see some of the most commonly used view modifiers for text in SwiftUI.
View Modifiers for Text view
Bold and Italic
If we want to make our text look bold or italic, we can use the bold() or italic() modifiers, respectively:
Text("Hello, World!")
.bold()
Text("Hello, World!")
.italic()
Color
We can also change the color of our text using the foreground color modifier. This modifier takes a color as a parameter. We can simply press the dot in the foreground color, and it will show us some of the colors present in SwiftUI. We can select any of them to make our text colorful.
Text("Hello, World!")
.foregroundColor(.red)
Alignment
The alignment modifier gives us the functionality to change the alignment of our text within its container. We can use the .leading, .center, and .trailing alignment options:
Text("Hello, world!")
.frame(width: 200, height: 50)
.background(Color.yellow)
.alignmentGuide(.leading) { _ in 50 }
Line Spacing and Line Limit
The lineSpacing and lineLimit modifiers allow us to change the spacing between lines and limit the number of lines of text, respectively:
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.lineSpacing(10)
.lineLimit(2)
Shadow
The shadow modifier adds a drop shadow to our text:
Text("Hello, world!")
.shadow(color: .gray, radius: 2, x: 2, y: 2)
In this example, we have added the shadow color gray and the radius 2 units. We have also given x and y directions to our text with 2 units.
Kerning
Text("Hello, world!")
.kerning(2)
In this example, We have increased the kerning by 2 units.
Strikethrough and Underline
If we want to add a strikethrough or underline to our text, we can use the strikethrough() and underline() modifiers:
Text("Hello, world!")
.font(.title)
.strikethrough()
Text("Hello, world!")
.font(.title)
.underline()
We can also select the color and style of the strikethrough or underline using additional parameters.
Tracking
The tracking modifier adjusts the spacing between groups of letters, also known as tracking:
Text("Hello, world!")
.font(.title)
.tracking(10)
Background Color
The background modifier allows us to set a background color for our text:
Text("Hello, world!")
.font(.title)
.background(Color.blue)
Conclusion
In this article, we have seen some of the Text View modifiers in SwiftUI. SwiftUI has a lot of rich View modifiers. We can use these modifiers to create a more attractive and eye-catching iOS app. Now we have covered all the modifiers for Text View in this article. Hope! You enjoyed this article.
Thank you for reading this article.