SwiftUI view modifers and dark mode

In SwiftUI, you can achieve most UI needs without ever explicitly checking for dark mode, thanks to semantic colours built into the platform and the ability to define our own semantic colours that automatically adapt to dark mode.

However, sometimes you might need to something explicit that the system can’t handle automatically. Maybe you want to remove a shadow from a view in dark mode, or use a different font.

Getting the current colour scheme inside a SwiftUI view is simple:

struct MyView: View {
    @Environment(\.colorScheme) var colorScheme: ColorScheme

    var body: some View {
        Text(colorScheme == .dark ? "Dark mode" : "Light mode")
    }
}

You can also do this inside view modifiers, so that your view logic can stay separate from your presentation logic:

struct FontModifier: ViewModifier {
    @Environment(\.colorScheme) var colorScheme: ColorScheme

    func body(content: Content) -> some View {
        let font: Font = colorScheme == .dark ? .system(size: 20) : .custom("Marker Felt", size: 20)
      return content.font(font)
    }
}

Just to reiterate the point: in most cases, you should use semantic colours and images to adapt your interfact for dark mode. This is how to do it manually for situations where that isn’t possible.

Thanks for reading.

To get in touch, email me or find me on Mastodon or Twitter.

If you liked this post, you'll love my iOS apps. Check them out below.

Personal Best

Level up your workouts

Taylor's Version

Upgrade Taylor Swift songs in your playlists

SalaryPig

Meet Trevor, the salary-tracking pig

Taylor Swift Quiz

How well do you know Taylor Swift?

Football Quiz

Test your soccer knowledge