Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for Dark Mode in iOS? [duplicate]

  • How to observe dark mode state in an iOS app
  • How to react to changes in dark mode state in an iOS app
like image 308
Marko Avatar asked Jun 05 '19 09:06

Marko


People also ask

How do I know if dark mode is enabled iOS?

Dark mode can be detected by using the userInterfaceStyle property on the current trait collection. When it's set to dark you know that the current appearance is set to dark.

How do you know if in dark mode Swift?

We simply have to add a @Enviroment variable and use . colorScheme property to scan the settings on our device and see if dark mode is enabled. Let's take a look at the example below. struct ContentView: View { @Environment(\.

What iOS has dark mode?

If you have an iPhone updated to iOS 13 or an Android phone that's updated to Android 10, your device will support system-wide dark mode.


1 Answers

UIKit has had UITraitCollection for a while now. Since iOS 9 you could use UITraitCollection to see whether the device supports 3D Touch (a sad conversation for another day)

In iOS 12, UITraitCollection got a new property: var userInterfaceStyle: UIUserInterfaceStyle which supports three cases: light, dark, and unspecified

Since UIViewController inherits UITraitEnvironment, you have access to the ViewController's traitCollection. This stores userInterfaceStyle.

UITraitEnviroment also has some nifty protocol stubs that help your code interpret when state changes happen (so when a user switches from the Dark side to the Light side or visa versa). Here's a nice coding example for you:

class MyViewController: UIViewController {      override func viewDidLoad() {         super.viewDidLoad()          if self.traitCollection.userInterfaceStyle == .dark {             // User Interface is Dark         } else {             // User Interface is Light         }      }       override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {         // Trait collection has already changed     }      override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {         // Trait collection will change. Use this one so you know what the state is changing to.     } }  
like image 60
Marko Avatar answered Sep 22 '22 08:09

Marko