Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add a Text View in SwiftUI
Written by Team Kodeco

Text views are one of the most common elements used in any SwiftUI user interface. They allow you to add text to your app, such as labels, titles, descriptions and more. In SwiftUI, Text views are simple to use, require minimal code, and offer a wide range of customization options.

To create a Text view, use the Text initializer and provide the text you want to display inside it. Here’s an example of how to create a Text view that displays a simple message:

struct ContentView: View {
  var body: some View {
    Text("Hello, World!")
  }
}

Inside the ContentView struct, we define the body computed property, which returns a view. Here, we use the Text view to create a new instance of a text view, with “Hello, World!” as its content.

Customizing a Text View With View Modifiers

The Text view is a flexible and lightweight view that allows you to customize its font, style, color, size, line spacing and more using modifiers. Here’s an example of how to customize the font style of the text view by adding a .font() modifier:

struct ContentView: View {
  var body: some View {
    Text("Hello, World!")
      .font(.headline)
  }
}

The above code uses the font modifier to define the font size and style of the Text view as .headline, one of SwiftUI’s predefined text styles. This is just one of the many modifiers that a Text view can incorporate. For a more comprehensive understanding, refer to the “Text & Fonts in SwiftUI” section.

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.