My App requires an initial view to be loaded programatically and not via the TabView. Here is an MRE to show the problem. The sequence is:
- ContentView loads the TabMenu
- The initial TabMenu View is OneView
- From the tabs you can switch between OneView and TwoView
How do I get the OneView to programatically load TwoView. It currently loses the Tab Menu (final screen shot below). In the full version of my code it was crashing to @main.
ContentView
import SwiftUI
struct ContentView: View {
@State var selectedTab = TabChoice.one
@State var calculated = CalculatedChoice.falseCC
var body: some View {
NavigationStack {
VStack {
// MARK: BUTTON
Spacer()
NavigationLink(destination: MenuView().navigationBarBackButtonHidden(true)) {
Text("Press to launch the TabView Menu")
.tint(.black)
}
Spacer()
}
}
.padding()
}
}
#Preview {
ContentView()
}
MenuView
import SwiftUI
enum TabChoice {
case one, two
}
enum CalculatedChoice {
case falseCC, trueCC
}
struct MenuView: View {
@State var selectedTab = TabChoice.one
@State var calculated = CalculatedChoice.falseCC
var body: some View {
NavigationStack {
VStack {
TabView(selection: $selectedTab) {
OneView(selectedTab: $selectedTab, calculated: $calculated)
.tabItem {
Label("One", systemImage: "1.circle")
}
.tag(TabChoice.one)
TwoView(selectedTab: $selectedTab, calculated: $calculated)
.tabItem {
Label("Two", systemImage: "2.circle")
}
.tag(TabChoice.two)
}
}
}
}
}
OneView
import SwiftUI
struct OneView: View {
@Binding var selectedTab: TabChoice
@Binding var calculated: CalculatedChoice
var body: some View {
VStack {
Spacer()
Text("TabView 1")
Spacer()
HStack{
NavigationLink(destination: TwoView(selectedTab: $selectedTab, calculated: $calculated).navigationBarBackButtonHidden(true)) {
Text("Press to Load TabView2 Programatically")
}
}
Spacer()
}
}
}
TwoView
import SwiftUI
struct TwoView: View {
@Binding var selectedTab: TabChoice
@Binding var calculated: CalculatedChoice
var body: some View {
VStack {
Spacer()
Text("TabView 2")
Spacer()
}
}
}
Many thanks to lorem ipsum for politely pushing me to create an MRE so the issues are clearer to see. Screen shots below: