Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Left-aligned SwiftUI Text view with a custom font.
Left-aligned SwiftUI Text view with a custom font.

Here’s what’s happening:

  1. You use the .custom parameter of the font modifier to set a blast-from-the-past typeface, specifying 24 point size.
  2. To change the font color, you use the foregroundColor modifier.
  3. To get the text to align left, you add a frame, setting the maxWidth to infinity, which says to stretch as far as possible horizontally, and then setting alignment to leading, which says to align to the leading edge of the parent view.
  4. Finally, you add some padding to 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”.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.