Turn on system dark mode from app - Swift

杀马特。学长 韩版系。学妹 提交于 2020-03-26 02:41:48

问题


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?


回答1:


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




回答2:


  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.



来源:https://stackoverflow.com/questions/57701467/turn-on-system-dark-mode-from-app-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!