Skip to content

Instantly share code, notes, and snippets.

@fl034
Last active September 15, 2023 07:00
Show Gist options
  • Save fl034/8f318cf9c2de64f6354bdee7f5c57f31 to your computer and use it in GitHub Desktop.
Save fl034/8f318cf9c2de64f6354bdee7f5c57f31 to your computer and use it in GitHub Desktop.
import SwiftUI
enum Tab: String, Identifiable, Hashable, CaseIterable {
case green, yellow, red
var id: String { rawValue }
}
struct ContentView: View {
// This needs to be set to the first tab.
@State var selectedTab: Tab = .green
// This can be set to another tab that you actually want to be set initially
@State var initiallySelectedTab: Tab? = .red
var body: some View {
NavigationStack {
TabView(selection: $selectedTab) {
Color.green.opacity(0.5)
.tag(Tab.green)
Color.yellow.opacity(0.5)
.tag(Tab.yellow)
Color.red.opacity(0.5)
.tag(Tab.red)
}
.tabViewStyle(.page(indexDisplayMode: .never))
.navigationTitle("Test")
.toolbar {
ToolbarItem {
Picker(selection: $selectedTab) {
ForEach(Tab.allCases) { element in
Text(element.rawValue)
.tag(element)
}
} label: {
Text(selectedTab.rawValue)
}
.pickerStyle(.menu)
}
}
.onAppear {
if let initiallySelectedTab {
self.initiallySelectedTab = nil
// Delay is needed to prevent SwiftUI bug where tapping the first tab wouldn't
// change views. This way every view will be loaded.
DispatchQueue.main.async {
self.selectedTab = initiallySelectedTab
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment