< How to create static labels with a Text view | How to adjust text alignment using multilineTextAlignment() > |
Updated for Xcode 14.0 beta 1
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")
.font(.largeTitle)
.frame(width: 300)
Download this as an Xcode project
We can control the color of text using the .foregroundColor()
modifier, like this:
Text("The best laid plans")
.foregroundColor(.red)
Download this as an Xcode project
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")
.padding()
.background(.yellow)
.foregroundColor(.white)
.font(.headline)
Download this as an Xcode project
Tip: You might wonder why 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")
.font(.largeTitle)
.lineSpacing(50)
.frame(width: 300)
Download this as an Xcode project
SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.