Exploring SwiftUI: Custom Colors and Modifiers
Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

Gradients Game (Image source: Author)

I have been working on my SwiftUI game for a few weeks now, and it’s turning out to be fun!

Custom Colors

I switched to custom colors for the branding, which is inspired by the systemIndigo color from UIColor. The above mockup uses systemIndigo, but I want to have a darker color for the light mode and a lighter color for the dark mode.

To achieve this, you can create a new color set in the Assets.xcassets folder.

Then tick-mark the Any, Dark appearances to have a different color in Dark Mode because why not?

Provide the values for the color(s). I used sRGB with a 0–255 method.

Create an extension of the struct color with a static constant, getting the color from the asset catalog.

extension Color {
    static let oldPrimaryColor = Color(UIColor.systemIndigo)
    static let newPrimaryColor = Color(primaryColor)
}

You can easily use it on a View like:

Text(Gradients Game)
    .fontWeight(.black)
    .font(.system(size: 36))
    .foregroundColor(.newPrimaryColor)

Custom Modifiers

If you look at the mockups above, both the Continue and Evaluate buttons have the same design.

You can achieve this by writing custom modifiers to reuse the design everywhere.

struct ButtonModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.headline)
            .foregroundColor(.white)
            .padding()
            .frame(width: UIScreen.main.bounds.width  30, alignment: .center)
            .background(RoundedRectangle(cornerRadius: 8, style:   .circular)
                .fill(Color.newPrimaryColor))
            .padding(.bottom, 8)
    }
}

To make it even simpler to use, write a function in an extension of the View to return the modifier.

extension View {
    func customButton() -> ModifiedContent<Self, ButtonModifier> {
        modifier(ButtonModifier())
    }
}

Now you can easily use it as:

Text(Evaluate).customButton()
Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

Written by

Rudrank Riyam

Hi, my name is Rudrank. I create apps for Apple Platforms while listening to music all day and night. Author of "Exploring MusicKit". Apple WWDC 2019 scholarship winner.