SwiftUI

Working With Text In SwiftUI

In this article, you’ll learn about all the modifiers you may need for laying out text in SwiftUI. Feel free to come back any time as a reference, this article has been designed to be an easy to use cheatsheet.

The Basics

To apply any one of the modifiers in this article, just add it to Text like this. Multiple modifiers can be used also.

Text("SwiftUI is Awesome")
  .font(.subtitle)

System Fonts

There are a few standard fonts to choose from such as .title

.font(.title)

Size

You can use the system font with a custom size.

.font(.system(size: 14))

Weight

Change font weight with this modifier

.fontWeight(.bold)

Multiple Modifiers

You can combine all of the above in one line like so.

.font(.system(size: 16, weight: .light, design: .default))

Colour

Changing the color of text is the same as any other view in SwiftUI

.foregroundColor(.gray)

Bold

To make text bold, use the following line.

.bold()

Italics

To italicize text, use the following line

.italic()

Text Alignment

To change text alignment, use .multilineTextAlignment

.multilineTextAlignment(.leading)

Line Spacing

Line spacing lets you change the amount of space between lines of text.

.lineSpacing(30)

Line Limit

You can set a limit to the amount of lines Text can take up.

.lineLimit(2)

Custom Fonts

It’s also possible to use custom fonts in SwiftUI. I like to do this through an extension like so.

extension Font {
  static let customTitle = custom("AvenirNext-Bold", size: 22)
  static let bodyText = custom("AvenirNext-Regular", size: 12)
}

Then you can just use the font like any other.

.font(.customTitle)

Conclusion

Hopefully this article has been helpful. Please feel free to use it as a reference in the future.