18

Is it possible in SwiftUI to force a View to use light or dark mode — like overrideUserInterfaceStyle in UIKit does?

ixany
  • 5,433
  • 9
  • 41
  • 65

2 Answers2

49

.colorScheme() is deprecated does not work with the background well.

.preferredColorScheme() is the way now. Does the job with the background too.

TestView1()
   .preferredColorScheme(.dark)

TestView2()
   .preferredColorScheme(.light)

Developer docs for .preferredColorScheme()

Jorge Frias
  • 1,077
  • 11
  • 13
  • 2
    In my case: `Text().background(.regularMaterial).preferredColorScheme(.dark)` did not work, but `Text().background(.regularMaterial).colorScheme(.dark)` did. That said, setting using `preferredColorScheme` higher up did work so – lewis Dec 06 '22 at 17:35
  • If we want to change the color scheme just to a view and not the entire presentation the `preferredColorScheme` will not help. Instead we can use `.environment(\.colorScheme, .dark)` – Busata Aug 17 '23 at 15:22
5

Use .colorScheme modifier, like

TestView1()
   .colorScheme(.dark)

TestView2()
   .colorScheme(.light)
Asperi
  • 228,894
  • 20
  • 464
  • 690