← Back to archive

Development · SwiftUI

Styling and aligning Text in SwiftUI

Control fonts, weight, alignment, spacing, and sizing when displaying text.

Read the Korean original on Velog ↗English translation

Development archive cover

Text is one of the most common views, but longer content raises questions about alignment, truncation, and size. These examples move from basic styling to the options needed for real sentences.

Modifiers

Modifiers add or change a view's properties.

Text("Hello, World!")
	.font(.title)

Text properties

Text-specific modifiers adjust its visual style and behavior.

Text("Hello, World!")
	.font(.body) // Body text style
    .fontWeight(.bold) // Bold weight
    .bold() // Bold text
    .foregroundColor(.blue) // Change the color
    .underline() // Underline
    .underline(true, color: Color.red) // Red underline
    .strikethrough(true, color: Color.green) // Green strikethrough
    .italic() // Italic text

System text styles

Use the .font modifier to apply a system font or semantic text style.

Text("Hello, World!")
	.font(.system(size: 24, weight: .semibold, design: .serif))
    // 24-point system font, semibold weight, serif design

A fixed font size such as 24 points does not adapt in the same way as a semantic style. Styles such as .body support Dynamic Type.

Text formatting

Adjust alignment and spacing to control how lines of text read together.

Text("Hello, World!")
	.multilineTextAlignment(.leading) // Leading alignment
    .multilineTextAlignment(.center) // Center alignment
    .multilineTextAlignment(.trailing) // Trailing alignment
    .baselineOffset(8.0) // Offset the text baseline
    .baselineOffset(-8.0) // A negative offset moves the baseline upward
    .lineSpacing(8) // Adjust line spacing
    .kerning(8) // Adjust character spacing

Frames

A frame proposes an area for the text and controls its placement. Without an explicit frame, text sizes itself according to its content and the space offered by its parent.

Text("Hello, World!")
	.frame(width: 200, height: 100, alignment: .center) // Fixed width and height with centered content
    .minimumScaleFactor(0.1) // Set the minimum scale for fitting text into the frame

Transforming text

Display transformations can change the presentation of text without changing the original string.

Text("Hello, World!".lowercased()) // Convert to lowercase
Text("Hello, World!".uppercased()) // Convert to uppercase
Text("Hello, World!".capitalized()) // Capitalize words
← Back to archive