Using gestures with TabView
In the preceding recipe, we learned how to switch between tabs by clicking 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 tabSelected = 0 ... }
- Replace the
Text
view in thebody
variable with aTabView
struct and some tabs:TabView(selection: $tabSelected){ Text("Left Tab. Click to switch to right") ...