如何通过视图控制器更改UIWindow背景颜色

问题描述

这个问题确实与此类似:How to set an app's UIWindow color when calling it from ViewController。但是,那里的解决方案不起作用。

自从苹果将窗口更改为位于场景委托(而不是应用程序委托)中以来,我一直无法更改场景委托之外的窗口(UIWindow)背景色(使用上述文章中的方法) )。有什么方法可以(通过视图控制器)调用Scene Delegate内部的函数,也可以在视图控制器中更改窗口背景颜色。我需要此功能的原因是因为我在应用程序内部处理了主题,并且当用户更改主题时,无论UIWindow颜色显示(例如, :展示一个视图控制器)。我尝试过的解决方案是:

if let window = UIApplication.shared.delegate?.window as? UIWindow {
    window.backgroundColor = .red
}

但这对我不起作用。

解决方法

您可以在任何controller中进行更改

  override func viewDidAppear(_ animated: Bool) {
          view.window?.backgroundColor = .red
    }

enter image description here