When I want to switch views between ChildOne and ChildTwo using the buttons, it works but I am sent to the Main view first.
I tried using a String variable instead of Bool, replacing @AppStorage with a simple @State/@Binding and also specifying @ViewBuilder above var body: some View but nothing worked.
import SwiftUI
struct ContentView: View {
@AppStorage("firstView") var firstView = true
var body: some View {
TabView {
MainView()
if firstView {
ChildOneView()
} else {
ChildTwoView()
}
}
}
}
struct ButtonsView: View {
@AppStorage("firstView") var firstView = true
var body: some View {
VStack {
Button("Show ChildOne", action: { firstView = true })
Button("Show ChildTwo", action: { firstView = false })
}
}
}
struct ChildOneView: View { // And also ChildTwoView
var body: some View {
VStack {
ButtonsView()
}
}
}
Do you have an idea why?
I think the problem there is that you are not marking the views as tabItems in the TabView, instead you are just placing the views there and SwiftUI by default selects the first one, in your case
MainView(). To solve it you just need to add the modifier.tabItem {}to each view and inside the braces set a label with the title and the image that you want to use in the tab.This would be the solution, placing .tabItem in each view to mark them as tabItems, by default SwiftUI does not know that the views that you are placing in the tabView are tabItems, you need to say to SwiftUI that that views are tabItems and also, you are getting into the MainView because it is the one that is placed first, if you place first any other view you will go to that view.