SwiftUI:强制视图使用明暗模式

ixa*_*any 2 swiftui ios-darkmode

在 SwiftUI 中是否可以强制 aView使用明暗模式——就像overrideUserInterfaceStyleUIKit 中那样?

小智 7

.colorScheme() 已弃用不适用于背景。

.preferredColorScheme()是现在的方式。也有背景的工作。

TestView1()
   .preferredColorScheme(.dark)

TestView2()
   .preferredColorScheme(.light)
Run Code Online (Sandbox Code Playgroud)

开发人员文档 .preferredColorScheme()

  • 如果我们只想更改视图而不是整个演示文稿的配色方案,则“preferredColorScheme”将无济于事。相反,我们可以使用 `.environment(\.colorScheme, .dark)` (5认同)
  • 就我而言:“Text().background(.regularMaterial).preferredColorScheme(.dark)”不起作用,但“Text().background(.regularMaterial).colorScheme(.dark)”起作用。也就是说,使用更高层的“preferredColorScheme”设置确实有效,所以 (3认同)

Asp*_*eri 5

使用 .colorScheme 修饰符,例如

TestView1()
   .colorScheme(.dark)

TestView2()
   .colorScheme(.light)
Run Code Online (Sandbox Code Playgroud)