NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to style text views with fonts, colors, line spacing, and more

Paul Hudson    @twostraws   

Updated for Xcode 12.5

Not only do text views give us a predictably wide range of control in terms of how they look, they are also designed to work seamlessly alongside core Apple technologies such as Dynamic Type.

By default a Text view has a “Body” Dynamic Type style, but you can select from other sizes and weights by calling .font() on it like this:

Text("This is an extremely long text string that will never fit even the widest of phones without wrapping")
    .frame(width: 300)

We can control the color of text using the .foregroundColor() modifier, like this:

Text("The best laid plans")

You can also set the background color, but that uses .background() because it’s possible to use more advanced backgrounds than just a flat color. Anyway, to give our layout a yellow background color we would add this:

Text("The best laid plans")

Tip: You might wonder why we used foregroundColor() has color in the name, whereas background() does not. This is because SwiftUI lets us recolor text however we want, but it must always be a simple color, whereas you can place any kind of view in the background – a color, yes, but also a shape, some other text, and more.

There are even more options. For example, we can adjust the line spacing in our text. The default value is 0, which means there is no extra line spacing applied, but you can also specify position values to add extra spacing between lines:

Text("This is an extremely long text string that will never fit even the widest of phones without wrapping")
    .frame(width: 300)
Hacking with Swift is sponsored by ViRE

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Download on the App Store

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.