Programmatically switching tabs on a TabView
In the preceding recipe, we learned how to switch between tabs by tapping on tab items at the bottom of the screen. However, we may also want to programmatically trigger tab switching. In this recipe, we will use a tap gesture to trigger the transition from one tab to another.
Getting ready
Create a new SwiftUI app named TabViewWithGestures.
How to do it…
We will create a TabView with two items, each containing some text that triggers a tab switch on click. The steps are given here:
- Open the ContentView.swift file, and add a @State variable to hold the value of the currently selected tab:
struct ContentView: View {
@State private var selectedTab = 0
...
}
- Replace the Text view in the body variable with a TabView, with two tab items:
var body: some View {
TabView(selection: $selectedTab) {
Text("Left Tab. Tap to switch to right")
.onTapGesture {
selectedTab...