SwiftUI Styling & Theming

SwiftUI Styling and Theming

A great app doesn't just function well; it looks beautiful.

SwiftUI provides incredible tools to apply consistent theming across your entire application.

From dynamic colors to scalable typography, SwiftUI makes modern app design effortless.


Semantic Colors and Dark Mode

iOS supports system-wide Light and Dark modes.

Instead of hardcoding colors like Color(red: 0, green: 0, blue: 0), you should use Semantic Colors.

Colors like Color.primary and Color.secondary automatically adapt! In Light mode, Color.primary is black. In Dark mode, it instantly flips to white.

Semantic Colors:

import SwiftUI

struct ThemedText: View { var body: some View { VStack { // Automatically black in light mode, white in dark mode! Text("Main Heading") .foregroundColor(.primary) // Automatically dark gray in light mode, light gray in dark mode! Text("Subheading") .foregroundColor(.secondary) } } }


Dynamic Type (Typography)

Users can change the default font size of their phone in the Settings app.

To support this, you should avoid hardcoding font sizes like .font(.system(size: 24)).

Instead, use semantic text styles like .largeTitle, .headline, and .body. SwiftUI will automatically scale these fonts up or down based on the user's preference.

Dynamic Typography:

struct TypographyView: View {
    var body: some View {
        Text("This text scales automatically!")
            .font(.headline)
            // Adding weight makes it bold but keeps it scalable
            .fontWeight(.bold) 
    }
}

Theming via the Environment

SwiftUI allows you to inject styles at the top level of your view hierarchy using the Environment.

If you apply a .font() or .foregroundColor() modifier to a VStack, that style cascades down and applies to every Text view inside it automatically!

Cascading Styles:

struct GlobalThemeView: View {
    var body: some View {
        VStack {
            Text("Item 1")
            Text("Item 2")
            Text("Item 3")
        }
        // Applied to ALL text inside the VStack
        .font(.title2)
        .foregroundColor(.blue) 
    }
}

Exercise

Which color should you use for your main text so that it automatically switches between black and white depending on Light/Dark mode?