A text view draws a string in your app’s user interface using a body
font that’s appropriate for the current platform. You can choose a different standard font, like title
or caption
, using the font(_:)
view modifier. Text views give us predictably wide range of controls 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 “Body” dynamic type style, but you can select from other sizes and weights by calling .font() on it like shown below.
Text("Sometimes we have to show extremely long text string that will never fit even the widest of phones without wrapping")
.font(.largeTitle)
.frame(width: 300)
We can control the color of text using the '.foregroundStyle()'
modifier, as shown below:
Text("The best is yet to come")
.foregroundStyle(.red)
.font(.largeTitle)
.frame(width: 300)
For more advanced text coloring, e.g. using a gradient, you should use 'foregroundStyle()'
like this:
Text("The best is yet to come")
.foregroundStyle(.blue.gradient)
.font(.largeTitle)
.frame(width: 300)
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 is yet to come")
.foregroundStyle(.white)
.font(.headline)
.frame(width: 300)
.padding()
.background(.yellow)
Apple offers more ways to configure text. 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("Sometimes we have to show extremely long text string that will never fit even the widest of phones without wrapping")
.font(.largeTitle)
.lineSpacing(50)
.frame(width: 300)
You can also use the 'fontDesign()
‘ modifier to adjust only the style of the font without also adjusting its size, as shown below.
Text("Hello, world!")
.font(.largeTitle)
.lineSpacing(50)
.frame(width: 300)
.fontDesign(.serif)
To compress or expand the font, use the fontWidth()
modifier as shown below.
Text("Hello, world!")
.font(.largeTitle)
.fontWidth(.condensed)
Pingback: How to add advanced text styling using AttributedString in swiftUI? – CoderzHeaven