Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Implementing Dark Mode Accessibility in SwiftUI
Written by Team Kodeco

Dark Mode, a feature that adjusts the color palette of user interfaces to darker colors, can enhance the viewing experience for users in low light environments. For visually impaired users, Dark Mode can also reduce screen glare and thus reducing eye strain. This chapter will show you how to accommodate Dark Mode in your SwiftUI app for a better user experience.

To create an app that supports Dark Mode, you should design your color assets and color schemes to adapt to both light and dark appearance. SwiftUI’s environment property colorScheme can be used to adjust the colors of your views based on the current appearance.

Here’s an example of how to adjust text color for light and dark appearance:

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

  var body: some View {
    Button("Hello, SwiftUI!", action: {})
      .padding()
      .foregroundColor(colorScheme == .dark ? .white : .black)
      .background(colorScheme == .dark ? .blue : .red)
      .cornerRadius(20)
  }
}

Select Color Scheme Variants from the Variants control at the bottom left of the preview canvas and you should see the following:

Color scheme variants in a SwiftUI view.
Color scheme variants in a SwiftUI view.

In this example, the Button view changes color based on the current color scheme. When in Dark Mode, the text is white on a blue background, and when in light mode, the text is black on a red background.

Additionally, you can use the .preferredColorScheme modifier to force a certain color scheme for testing purposes or user preferences:

struct ContentView: View {
  var body: some View {
    Text("Hello, SwiftUI!")
      .foregroundColor(.white)
      .background(.black)
      .preferredColorScheme(.dark)
  }
}

Your preview should now look like:

Preferred color scheme in a SwiftUI view.
Preferred color scheme in a SwiftUI view.

In this case, regardless of the system settings, the view will always be displayed in Dark Mode.

By thoughtfully designing your color schemes and applying the appropriate modifiers, you can ensure your SwiftUI app provides a great user experience in both light and dark modes, contributing to its overall accessibility.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.