首页 > 解决方案 > iOS 浅色模式和深色模式

问题描述

我想在我的应用程序中拥有一项功能。我决定创建 UIAlertController 和 2 AlertAction:Light Mode 和 Dark Mode。如何通过单击其中一个 AlertAction 来更改整个应用程序的模式。请帮忙 ....

标签: iosswiftios-darkmode

解决方案


@available(iOS 13.0, *)
func changeMode() {

      let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
          alertController.addAction(UIAlertAction(title: "DARK MODE", style: .default, handler: { action in

           UIWindow.animate(withDuration: 0.5, animations: {
                 UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = .dark
                //also try : UIApplication.shared.windows.last?.overrideUserInterfaceStyle = .dark
                })
         }))

          alertController.addAction(UIAlertAction(title: "LIGHT MODE", style: .default, handler: { action in

           UIWindow.animate(withDuration: 0.5, animations: {
                 UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = .light
                 //UIApplication.shared.windows.last?.overrideUserInterfaceStyle = .light

                })

          }))

    self.present(alertController, animated : true)

}

推荐阅读