iosswiftswiftuiswiftui-tabview

SwiftUI - How to set color scheme only for specific tabs in TabView?


I have a TabView with two tabs, and I want the first tab to have color scheme of light and the second tab to have color scheme of dark.

I've tried this:

struct ContentView: View {
    var body: some View {
        TabView {
            Tab("Tab 1", systemImage: "video") {
                FirstView()
                    .preferredColorScheme(.light)
            }
            Tab("Tab 2", systemImage: "person") {
                SecondView()
                    .preferredColorScheme(.dark)
            }
        }
    }
}

Then both tabs are in light scheme.

I've also tried this:

struct ContentView: View {
    var body: some View {
        TabView {
            Tab("Tab 1", systemImage: "video") {
                FirstView()
            }
            Tab("Tab 2", systemImage: "person") {
                SecondView()
                    .preferredColorScheme(.dark)
            }
        }
    }
}

Then at the beginning tab 1 is light, and when I switch to tab 2, tab 2 is dark, but then if I switch to tab 1 again, then tab 1 becomes dark!

So what should I do?


Solution

  • try this approach using a selectedTab, for example:

    
    struct ContentView: View {
        @State private var selectedTab = 0  
        
        var body: some View {
            TabView(selection: $selectedTab) {  
                Tab("Tab 1", systemImage: "video", value: 0) { 
                    FirstView()
                }
                Tab("Tab 2", systemImage: "person", value: 1) { 
                    SecondView()
                }
            }
            .preferredColorScheme(selectedTab == 0 ? .light : .dark) 
        }
    }