black and silver laptop computer on table

100 Days of SwiftUI – Project 3: Views and Modifiers

This project is a deep dive into various advanced capabilities and features of views and modifiers.

Today we get a little bit of information about why some things (like struct and View) are the way they are in SwiftUI. We also learn about conditional modifiers, environment modifiers and how to make and use our own modifiers. Finally we’re shown how to make and use custom views, and told why we’d want to, before moving on to the challenge.

Challenge

Today’s challenge involves going back to our previous projects and making some changes, as well as making our own custom modifier.

WeSplit conditional modifier

First up, we’re asked to highlight the total check in red text if the tip percentage is 0% using a conditional modifier.

Text(grandTotal, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
  .foregroundStyle(tipPercentage == 0 ? .red : .black)

Guess the Flag custom view

In Guess the Flag we’re asked to create a new custom view that displays the flag image with the appropriate modifiers. First I create the view itself.

struct FlagImage: View {
    var image: String
    
    var body: some View {
        Image(image)
            .clipShape(.capsule)
            .shadow(radius: 5)
    }
}

And then replace the original Image call with the new FlagImage one.

ForEach(0..<3) { number in
    Button {
        flagTapped(number)
    } label: {
        FlagImage(image: countries[number])
    }
}

Custom modifier

The last challenge is to create a custom modifier for text to make it large and blue.

struct Title: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.largeTitle)
            .foregroundStyle(.blue)
    }
}

extension View {
    func titleStyle() -> some View {
        modifier(Title())
    }
}

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .titleStyle()
    }
}

Solution