繁体   English   中英

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

[英]Turn on system dark mode from app - Swift

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

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

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

  • 第一个问题:目前不可能
  • 第二个问题: 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 开发者文档

当iOS界面环境发生变化时,系统会调用该方法。 根据您的应用程序的需要,在视图控制器和视图中实现此方法以响应此类更改。 例如,当 iPhone 从纵向旋转到横向时,您可能会调整视图控制器子视图的布局。 此方法的默认实现为空。

系统默认 UI 元素(例如UITabBarUISearchBar )会自动适应新的用户界面样式。

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

使用此方法您将获得亮模式和暗模式,将此代码放入开关中,您的视图将根据暗和亮的外观而变化。

  • 第一个问题:在 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 }
  • 第二个问题:在VC中使用Toggle Switch

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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