SwiftUI Text View complete tutorial

Text is a view in SwiftUI which displays one or more lines of text. Experiment with the code presented below on your own to get a feel of how to work with Text view in practice.

In its simplest form, to display one line of text, use it like that:

Text("SwiftUI Text View Tutorial")

To display multiple lines of text, use a new line character as a separator:

Text("Simple Swift Guide\nSwiftUI Text View Tutorial")

Style the text view to make it bold, italic and underlined:

Text("Simple Swift Guide")
    .bold()
    .italic()
    .underline()

Apply strikethrough to the text:

Text("Simple Swift Guide").strikethrough()

Change the font weight of the text:

Text("Simple Swift Guide").fontWeight(.ultraLight)

Change font type of the text (e.g., to use defined, system wide large title):

Text("Simple Swift Guide").font(.largeTitle)

Change color of the text:

Text("Simple Swift Guide").foregroundColor(Color.red)

Change background color of the entire Text view:

Text("Simple Swift Guide").background(Color.red)

Uniformly add extra space (in points) between individual text characters (e.g., spread characters apart):

Text("Simple Swift Guide").tracking(0.8)

To bring the characters closer together, use negative value for tracking:

Text("Simple Swift Guide").tracking(-0.6)

Join multiple Text views together to form a single Text view:

Text("Simple ") + Text("Swift ") + Text("Guide")

If your text is expected to be long and will automatically wrap to form multiple lines, you can explicitly limit the number of lines:

Text("A very long sentence").lineLimit(1)

Create a tag-like Text view pill with custom padding and corner radius:

Tag-like Text view pill.
Tag-like Text view pill.
Text("SwiftUI")
    .font(.title)
    .padding(10.0)
    .background(Color.blue)
    .foregroundColor(Color.white)
    .cornerRadius(18.0)

Related tutorials:

Check out Apple’s official documentation of Text view to learn more.