Day 19 – SwiftUI Styling & Modifiers
T
Tuan Beo

Day 19 – SwiftUI Styling & Modifiers

Learn to style your SwiftUI views with fonts, colors, shadows, padding, and custom modifiers to make your UI visually appealing.

1️⃣ Styling Basics

Every SwiftUI view can be styled using modifiers.

Example:

Text("Hello, Vy!")
    .font(.title)                // bigger text
    .foregroundColor(.blue)      // change text color
    .padding()                   // space around view
    .background(Color.yellow)    // background color
    .cornerRadius(10)            // rounded corners

2️⃣ Applying Styles to To-Do List Rows

Let’s make our task rows more appealing.

HStack {
    Image(systemName: task.isDone ? "checkmark.circle.fill" : "circle")
        .foregroundStyle(task.isDone ? .green : .gray)
        .imageScale(.large)

    VStack(alignment: .leading) {
        Text(task.title)
            .font(.headline)
            .strikethrough(task.isDone)
            .foregroundStyle(task.isDone ? .secondary : .primary)

        if !task.notes.isEmpty {
            Text(task.notes)
                .font(.subheadline)
                .foregroundStyle(.secondary)
        }
    }
    Spacer()
}
.padding(.vertical, 8)
.background(
    RoundedRectangle(cornerRadius: 12)
        .fill(Color(.systemBackground))
        .shadow(color: .black.opacity(0.1), radius: 3, x: 0, y: 2)
)
.listRowSeparator(.hidden) // iOS 15+

3️⃣ Using Custom ViewModifiers

Instead of repeating styles everywhere, we can create reusable modifiers.

struct CardStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color(.systemBackground))
                    .shadow(color: .black.opacity(0.1), radius: 3, x: 0, y: 2)
            )
    }
}

extension View {
    func cardStyle() -> some View {
        self.modifier(CardStyle())
    }
}

Now just use:

VStack {
    Text("Task Title")
}.cardStyle()

4️⃣ Color & Theming

Use SwiftUI’s built-in adaptive colors for dark/light mode:

Color.primary     // adjusts automatically
Color.secondary
Color(.systemBackground)
Color(.label)     // iOS UIColor

You can also define custom colors in Assets.xcassets and use:

Color("CustomColorName")

5️⃣ Fonts

SwiftUI has predefined styles:

.font(.largeTitle)
.font(.headline)
.font(.body)
.font(.caption)

Or custom fonts (add .ttf to your project, then):

.font(.custom("FontName", size: 18))

6️⃣ Spacing & Alignment

.padding(.horizontal, 16)
.frame(maxWidth: .infinity, alignment: .leading)

🛠 Practice

  1. Make your To-Do rows look like “cards” with shadows & rounded corners.

  2. Add color-coded priorities (e.g., high priority = red dot).

  3. Add a subtle gradient background to the main screen.

  4. Create a reusable PriorityBadge view for showing task priority.

Comments