How to Check User Interface Appearance

Is it possible to check whether the user has dark/light mode enabled and adjust an interface accordingly? I’m looking to do this with colors in SpriteKit (or anything other than UIKit or SwiftUI, technically) based on the device’s global setting rather than an app setting.

Replies

Detecting Dark Mode Programmatically

There may be some cases in which you want to detect appearance changes programmatically and change your user interface accordingly.

⚠ Warning: When responding to appearance changes, make sure to update your interface as quickly as possible. Do not perform tasks that are unrelated to the appearance change, as it may result in delays, especially if the user switches appearance from Control Center.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection)  let userInterfaceStyle = traitCollection.userInterfaceStyle // Either .unspecified, .light, or .dark // Update your user interface based on the appearance }

Detecting appearance changes is trivial by overriding

traitCollectionDidChange
on view controllers. Then, just access the view controller’s
traitCollection.userInterfaceStyle
.

However, it is important to remember that

traitCollectionDidChange
may be called for other trait changes, such as the device rotating. You can check if the current appearance is different using this new method:
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection)  let hasUserInterfaceStyleChanged = previousTraitCollection.hasDifferentColorAppearance(comparedTo: traitCollection) // Bool // Update your user interface based on the appearance }

If you want to access the current trait collection from anywhere, you can also use

UITraitCollection.current
.