Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Change color theme programmatically

Tags:

swiftui

I have .light and .dark theme.

In preview (MyContainer_Previews) I can change them by:

ForEach([.light,.dark], id: \.self) { theme in

            Group {
                ...
            } 
            .environment(\.colorScheme, theme) //This line
        }
 ...

How can I change app theme on the fly (f.e. button action). I tri to change it in SceneDelegate:

 let contentView = ContentView()
 contentView.environment(\.colorScheme, .dark) //Not work
like image 790
Tim Avatar asked Nov 13 '19 15:11

Tim


2 Answers

Reactive:

    return NavigationView {
        VStack(alignment: .trailing, spacing: 0) {
            ...
        }

    } 
    .environment(\.colorScheme, appState.options.theme == .light ? .light : .dark)
like image 127
Tim Avatar answered Oct 25 '22 19:10

Tim


Some one told me if you put you code in NavagationView, you can use your enviorment to change the scheme.

var body: some View {


NavigationView{
   //Your view here
}}

let contentView = ContentView() contentView.environment(\.colorScheme, .dark) //works now

  UIHostingController(rootView: ContentView().environment(\.colorScheme, .light)

  struct ContentView: View {
var body: some View {
   NavigationView{
       Text("!")
    }}}
like image 22
E.Coms Avatar answered Oct 25 '22 18:10

E.Coms