从应用程序打开系统黑暗模式 - Swift

Turn on system dark mode from app - Swift

我使用 Notifications 在我的应用程序上创建了自己的暗模式系统,并且我有一个开关可以在暗模式打开和关闭之间切换。

我的第一个问题:如何打开系统黑暗模式,如果通过拨动开关更新到iOS 13,整个phone也会变成黑暗模式。

我的第二个问题:如何检查系统暗模式是否启用,以便在 iOS 系统暗模式启用时,我可以在启用暗模式的地方设置?

  • 第一个问题:暂时不可能
  • 第二个问题: of Tamás Sengel

您应该检查 UITraitCollectionuserInterfaceStyle 变量,与 tvOS 和 macOS 相同。

switch traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}

您应该使用UIView/UIViewControllertraitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)功能来检测界面环境的变化(包括用户界面风格的变化)。

来自 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.

系统默认UI个元素(例如UITabBarUISearchBar)自动适应新的用户界面风格。

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

用这个方法你会得到浅色模式和深色模式,将这段代码放入开关,你的视图就会根据深色和浅色的外观而变化。