Skip to main content

How to detect dark mode

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to detect dark mode 관련

SwiftUI by Example

Back to Home

How to detect dark mode | SwiftUI by Example

How to detect dark mode

Updated for Xcode 15

SwiftUI lets us detect whether dark mode or light mode is currently enabled using the colorScheme environment key. If you declare this using @Environment, you can refer to it in your views and they will automatically be reloaded when the color scheme changes.

For example, this will print either “In dark mode” or “In light mode” depending on the current color scheme:

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

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

This should generally only be necessary for custom drawing – if you want to enable dark and light colors or dark and light images these can both be done using your asset catalog, and will also reload when the color scheme changes.

Similar solutions…
How to show different images and other views in light or dark mode | SwiftUI by Example

How to show different images and other views in light or dark mode
How to preview your layout in light and dark mode | SwiftUI by Example

How to preview your layout in light and dark mode
How to customize the display mode of NavigationSplitView | SwiftUI by Example

How to customize the display mode of NavigationSplitView
How to detect the location of a tap inside a view | SwiftUI by Example

How to detect the location of a tap inside a view
How to detect device rotation | SwiftUI by Example

How to detect device rotation

이찬희 (MarkiiimarK)
Never Stop Learning.