How to only apply preferred color scheme to one view and not the rest of the views in the view hierarchy in SwiftUI

Viewed 236

I am trying to make one view render in dark mode while the rest of my app is in the users chosen color scheme. When I apply .preferredColorScheme(.dark) to the subview, it causes other views to turn dark as well. How can I fix this behavior?

ContentView:

NavigationView {
    ZStack {
        NavigationLink(isActive: $showingGoalDashboardView) {
            TestView(goal: goals.first!)
        } label: {
            EmptyView()
        }
                
        NavigationLink(isActive: $showingCreateGoalView) {
            CreateGoalView(showingGoalCreateView: $showingCreateGoalView)
        } label: {
            EmptyView()
        }
                
        LoadingView()
    }
}

LoadingView: LoadingView just contains some UI elements, all wrapped in a ZStack with the property .preferredColorScheme(.dark) applied to it.

1 Answers

The preferredColorScheme works NOT per-view, but for current presentation - which in this case is a current window. See documentation:

demo

Put LoadingView into sheet or popover, or new window, etc, and there dark mode will be applied independently.

Update: well, actually it can still be used View.colorScheme, and it works, but it has been deprecated - just be aware:

    LoadingView()
        .colorScheme(.dark)

Tested with Xcode 13.4 / iOS 15.5

Related