0
0
Ios-swiftHow-ToBeginner ยท 3 min read

How to Use Font Modifier in SwiftUI: Syntax and Examples

In SwiftUI, use the font modifier to change the font style, size, and weight of text views. Apply it directly to a Text view like Text("Hello").font(.title) to set a predefined font style.
๐Ÿ“

Syntax

The font modifier is used on a Text view to set its font style. You can use predefined fonts like .title, .body, or create custom fonts with size and weight.

  • Text("Hello").font(.title) sets a large title font.
  • Text("Hello").font(.system(size: 20, weight: .bold)) sets a custom system font size and weight.
swift
Text("Hello World").font(.title)
Output
Displays the text "Hello World" in a large title font style.
๐Ÿ’ป

Example

This example shows how to apply different font styles and custom fonts to text in SwiftUI.

swift
import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack(spacing: 20) {
      Text("Title Font").font(.title)
      Text("Body Font").font(.body)
      Text("Custom Font").font(.system(size: 24, weight: .semibold, design: .rounded))
    }
    .padding()
  }
}
Output
A vertical stack showing three texts: "Title Font" in large title style, "Body Font" in default body style, and "Custom Font" in 24pt semibold rounded system font.
โš ๏ธ

Common Pitfalls

Common mistakes include applying the font modifier to views other than Text, which has no effect, or forgetting to chain the modifier properly.

Also, using unsupported font names in custom fonts will cause the text to fallback to the default font.

swift
/* Wrong: font modifier on a VStack has no effect */
VStack {
  Text("Hello")
}.font(.title)

/* Right: font modifier applied directly to Text */
Text("Hello").font(.title)
Output
Only the second example changes the text font to title style; the first example does not change the font.
๐Ÿ“Š

Quick Reference

Font Modifier UsageDescription
.font(.largeTitle)Sets text to large title font style
.font(.body)Sets text to default body font style
.font(.system(size: 16))Sets system font with custom size 16
.font(.system(size: 18, weight: .bold))Sets system font size 18 with bold weight
.font(.custom("FontName", size: 20))Sets a custom font by name and size
โœ…

Key Takeaways

Use the font modifier directly on Text views to change their font style.
You can use predefined fonts or create custom fonts with size, weight, and design.
Applying font to non-Text views has no effect.
Always verify custom font names are correctly added to your project.
Chain modifiers properly to ensure font changes apply as expected.