I have the following simplified code in a project using XCode 13.2. The intended functionality is to have 2 tabs (Tab1
and Tab2
), and the user is able to tap the screen on Tab2
to toggle the background from red to green.
Instead, however, when Tab2
is clicked, the screen displays tab 1, instead of Tab2
with the changed color. I'm wondering why the app goes to Tab1
when Tab2
is tapped.
There are no NavigationLinks or actions that make the user go to Tab1
. My only thought is that maybe the app is rebuilding when Tab2
is clicked, which is why it goes back to the first tab? If so, are there any good workarounds for this?
Note: the color still changes on Tab2
, but not before the app switches to Tab1
.
struct ContentView: View {
var body: some View {
TabView {
Tab1()
.tabItem {
Text("Tab 1")
}
Tab2()
.tabItem {
Text("Tab 2")
}
}
}
}
struct Tab1: View {
var body: some View {
Text("Tab 1")
}
}
struct Tab2: View {
@State var isRed: Bool = false
var body: some View {
if !isRed {
Color.green
.onTapGesture {
isRed = true
}
} else {
Color.red
.onTapGesture {
isRed = false
}
}
}
}