SwiftUI Text View Tutorial

The text view is a view that displays one ore more lines of read-only text. In this tutorial the text views will be modified with different type of modifiers. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUITextViewTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

var body: some View {
    VStack {
        // 1.
        Text("Hello World")

        // 2.
        Text("Dynamic Types Example")

        // 3.
        Text("Color Example")

        // 4.
        Text("Kerning Example")

        // 5.
        Text("Style Example")

        // 6.
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")

        // 7.

        // 8.
        // 9.
  1. The default usage of the text view to display a string

  2. The default dynamic type is “body”. The dynamic type can be changed with the .font() modifier. Possible values are largeTitle, title, headline, subheadline, body, callout, footnote and caption.

  3. The text color and the background color can be changed with the .foregroundColor() and .background() modifier.

  4. Kerning is the amount of spacing to use between individual characters and can be changed with the .kerning() modifier.

  5. A style can be applied to the text with a style modifier. Possible values are bold(), italics(). strikethrough() and underline().

  6. By default, text will be displayed on one line and will be truncated at the end.

  7. The number of visible lines can be modified with the .linelimit() modifier. By assigning nil all lines will be visible.

  8. The spacing between lines can be modified with the .lineSpacing() modifier and defaults to 0.

  9. Multiple lines can be aligned with the .multiLineTextAlignment() modifier

The preview will look like this.

The source code of the SwiftUITextViewTutorial can be downloaded at the ioscreator repository on Github.