Hello,
I have an app with a swiftUI tabBar. It as been working fine for weeks of development.
Recently I wanted to persist the selected tab using UserDefaults. The persisting seems to be happening correctly, however my tabBar will now only display the initially selected tab. Trying to switch to another tab just displays a blank view.
Is there something wrong in this sample code?
I have an app with a swiftUI tabBar. It as been working fine for weeks of development.
Recently I wanted to persist the selected tab using UserDefaults. The persisting seems to be happening correctly, however my tabBar will now only display the initially selected tab. Trying to switch to another tab just displays a blank view.
Is there something wrong in this sample code?
Code Block struct ContentView: View { var body: some View { TabView(selection: Binding<Int>( get: { Defaults.shared.selectedTabIndex }, set: { Defaults.shared.selectedTabIndex = $0 } )) { FirstTab() .tabItem { Text("First") } .tag(0) SecondTab() .tabItem { Text("Second") } .tag(1) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct FirstTab: View { var body: some View { Text("Tab1") } } struct SecondTab: View { var body: some View { Text("Tab2") } } class Defaults { static let shared = Defaults() var selectedTabIndex: Int { didSet { UserDefaults.standard.set(selectedTabIndex, forKey: "selectedTabIndex") } } init() { selectedTabIndex = UserDefaults.standard.integer(forKey: "selectedTabIndex") } }