Styling Text in SwiftUI
Written by Team Kodeco
When designing a user interface, the way text is displayed can be just as important as the content itself. Fortunately, SwiftUI gives you powerful tools for styling text exactly how you want it.
To get started, create a simple “Hello, world!” Text view:
struct ContentView: View {
var body: some View {
Text("Hello, world!")
}
}
By default, SwiftUI text views align center, using the system font at the default size and color. But what if you want to change these things? Try the following and see how you can get more interesting formatting by chaining view modifiers:
struct ContentView: View {
var body: some View {
Text("Hello, 1982 world!")
// 1
.font(.custom("Papyrus", size: 24))
// 2
.foregroundColor(.purple)
// 3
.frame(maxWidth: .infinity, alignment: .leading)
// 4
.padding()
}
}
The preview should look as follows:
Here’s what’s happening:
- You use the
.customparameter of thefontmodifier to set a blast-from-the-past typeface, specifying 24 point size. - To change the font color, you use the
foregroundColormodifier. - To get the text to align left, you add a
frame, setting themaxWidthtoinfinity, which says to stretch as far as possible horizontally, and then settingalignmenttoleading, which says to align to the leading edge of the parent view. - Finally, you add some
paddingto prevent the text from being smooshed right up against the lefthand side of the screen.
Learn more about formatting text in SwiftUI throughout this section, as well as in “Theming & Styling in SwiftUI” and “Accessibility in SwiftUI”.