Dark Mode
Dark Mode is an important feature that many users appreciate for its aesthetic appeal, and for people with visual impairments.
When do we need Dark Mode support?
Dark Mode support is essential.
supporting Dark Mode can enhance accessibility for users with visual impairments who may find it easier to read content on a dark background.
How to implement Dark Mode in SwiftUI
Implementing Dark Mode in SwiftUI is straightforward. SwiftUI mostly adapts automatically to the system's appearance settings, you may use a theming system to use dark and light colors without reading the environment variable .colorScheme all the time.
Automatic Support
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("SwiftUI Will Handle Dark Mode Automatically")
.foregroundColor(.primary)
.background(.background)
}
}
}
Custom View
struct ThemedView: View {
@Environment(\.colorScheme)
var colorScheme
var foregroundColor: Color {
colorScheme == .dark ? .black : .white
}
var backgroundColor: Color {
colorScheme == .dark ? .white : .black
}
var body: some View {
Text("This view adapts to Dark Mode, using custom colors!")
.foregroundColor(foregroundColor)
.background(backgroundColor)
}
}
Use Assets Catalog
You can define colors in your Assets catalog that automatically adapt to Light and Dark modes. When you create a new color set, you can specify different colors for "Any Appearance" and "Dark Appearance".
Forcing interface style
If you want to force a specific interface style for a view or the entire app, you can use the .preferredColorScheme(_:) modifier:
struct ForcedDarkModeView: View {
var body: some View {
VStack {
Text("This view is always in Dark Mode")
}
.preferredColorScheme(.dark)
}
}
Libraries and Tools:
My package Colors provides a convenient way to manage colors in your SwiftUI projects, including support for Dark Mode. You can define colors that automatically adjust based on the current appearance.
Wrap up
SwiftUI handles most of Dark Mode automatically — using semantic colors and .preferredColorScheme(_:) is all most apps need. Read the \.colorScheme environment value only when you genuinely need to branch behavior.
Resources:
Read more
- Surprise Route • 4 minutes reading time.
- Creating macOS Menu Bar App in SwiftUI • 4 minutes reading time.
- Hidden macOS features • 3 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook