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

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

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:

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

Then I found that both tabs are in light scheme.

I've also tried this:

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

I found that 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?

Answer

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) } }

Related Articles