简体   繁体   中英

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?

  • 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.

  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.

  • First question: In AppDelegate

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let darkModeStatus = UserDefaults.standard.bool(forKey: "darkModeStatus") if darkModeStatus == true { window?.overrideUserInterfaceStyle = .dark } else { window?.overrideUserInterfaceStyle = .light } return true }
  • Second Question: with Toggle Switch in VC

     @IBAction func darkModeSwitchClicked(_ sender: Any) { if darkModeToggleSwitch.isOn { UserDefaults.standard.set(true, forKey: "darkModeStatus") } else { UserDefaults.standard.set(false, forKey: "darkModeStatus") } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM