enigrify
enigrify

Reputation: 301

Turn on system dark mode from app - Swift

I have made my own system of dark mode on my app using Notifications and I have a switch that changes between dark mode on and off.

My first question: How do I turn on system dark mode, where the whole phone becomes dark mode as well if it is updated to iOS 13 by flipping the switch.

My second question: How do I check to see if system dark mode is enabled so that I can make it where my dark mode is enabled whenever the iOS system dark mode is enabled?

Upvotes: 1

Views: 4076

Answers (2)

Syed Haris
Syed Haris

Reputation: 21

  if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = .light // or .dark 
        } else {
            // Fallback on earlier versions
        }

with this method you will get the light mode and dark mode, put this code into switch and your view will changes according to dark and light appearance.

Upvotes: 1

えるまる
えるまる

Reputation: 2551

  • First question: Impossible at this moment
  • Second Question: Answer of Tamás Sengel

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.

Upvotes: 1

Related Questions