How can I check whether dark mode is enabled in iOS/iPadOS?
For iOS 13, you can use this property to check if current style is dark mode or not:
if #available(iOS 13.0, *) {
if UITraitCollection.current.userInterfaceStyle == .dark {
print("Dark mode")
}
else {
print("Light mode")
}
}
You should check the userInterfaceStyle
variable of UITraitCollection
, same as on tvOS and macOS.
switch traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
You should use the traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
function of UIView
/UIViewController
to detect changes in the interface environment (including changes in the user interface style).
From Apple Developer Documentation:
The system calls this method when the iOS interface environment changes. Implement this method in view controllers and views, according to your app’s needs, to respond to such changes. For example, you might adjust the layout of the subviews of a view controller when an iPhone is rotated from portrait to landscape orientation. The default implementation of this method is empty.
System default UI elements (such as UITabBar
or UISearchBar
) automatically adapt to the new user interface style.