Home > Blockchain >  Swift if statement in modifier
Swift if statement in modifier

Time:04-15

So I have an basic Taskview:

TabView {
    NavigationView {
        TasksView()
    }
    .tabItem {
        Image(systemName: "bookmark")
        Text("Tasks")
    }
    
    NavigationView {
        ShopView()
    }
    .tabItem {
        Image(systemName: "cart.fill")
        Text("Shop")
    }
}
.environment(\.colorScheme, isDarkMode ? .dark : .light)

And now I want to add an if statement to .environment. So like if Default: .environment(.colorScheme, isDarkMode ? .dark : .light)

How can I do this?

CodePudding user response:

Use @Environment to call the current color scheme. Then you can create a color variable.

struct ContentView: View {
    @Environment(\.colorScheme) private var colorScheme
    
    var body: some View {
        TabView {
            NavigationView {
                TasksView()
            }
            .tabItem {
                Image(systemName: "bookmark")
                Text("Tasks")
            }
            .foregroundColor(titleColor) // <- here
            NavigationView {
                ShopView()
            }
            .tabItem {
                Image(systemName: "cart.fill")
                Text("Shop")
            }
            .foregroundColor(titleColor) // <- here
        }
    }
    
    private var titleColor: Color {
        switch colorScheme {
        case .light:
            return .red
        case .dark:
            return .yellow
        @unknown default:
            return .blue
        }
    }
}

CodePudding user response:

Here's a possible solution. Use an ObservableObject class, store and save the variable. Set it as a StateObject and set as environmentObject in your App, then you can handle updates in your View by accessing the variable.


class ColorScheme: ObservableObject {
    @AppStorage("dark") var dark = false
}

 
struct MyApp: App {
    @StateObject var colorscheme = ColorScheme()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(colorscheme)
                .colorScheme(colorscheme.dark ? .dark : .light)
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var colorscheme: ColorScheme
    var body: some View {
        NavigationView {
            List {
                Toggle("Color Scheme", isOn: colorscheme.$dark)
            }
        }
    }
}

dark light

  • Related