I find that that on iOS, e.g. on 17.2, that if a TabView’s selection is set and then set again before the tab swipe animation completes, then the selection state gets out of sync with the tab that’s shown.
In this example, if you tap “Go to tab 2” twice quickly, before the animation to tab 2 completes, then the animation to tab 2 is canceled, the screen stays on tab 1, but the selection state value stays as 2.
I found a workaround which I coded on tab 2, which is to check if the state value is already the new value, and reset it to another value before setting it to the desired value. However is there a better workaround so that the selection state value is always the actual tab that is shown? Thank you
import SwiftUI
struct ContentView: View {
@State private var activeTab = 1
var body: some View {
TabView(selection: $activeTab) {
VStack {
Text("Tab 1")
Button {
withAnimation {
activeTab = 2
}
} label: {
Label("Go to tab 2", systemImage: "arrow.right")
}
}
.tag(1)
VStack {
Text("Tab 2")
Button {
if activeTab == 1 {
activeTab = 2
}
withAnimation {
activeTab = 1
}
} label: {
Label("Go to tab 1", systemImage: "arrow.left")
}
}
.tag(2)
}
.tabViewStyle(.page)
.indexViewStyle(.page(backgroundDisplayMode: .always))
}
}
@main
struct TestTabViewApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}