Search code examples
swiftswiftuitabviewswiftui-tabviewswiftui-ontapgesture

SwiftUI TabView: how to detect click on a tab?


I would like to run a function each time a tab is tapped.

On the code below (by using onTapGesture) when I tap on a new tab, myFunction is called, but the tabview is not changed.

struct DetailView: View {
    var model: MyModel
    @State var selectedTab = 1
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Graphs").tabItem{Text("Graphs")}
               .tag(1)
            Text("Days").tabItem{Text("Days")}
               .tag(2)
            Text("Summary").tabItem{Text("Summary")}
               .tag(3)
        }
        .onTapGesture {
            model.myFunction(item: selectedTab)
        }
    }
}

How can I get both things:

  • the tabview being normally displayed
  • my function being called

Solution

  • As of iOS 14 you can use onChange to execute code when a state variable changes. You can replace your tap gesture with this:

    .onChange(of: selectedTab) { newValue in
        model.myFunction(item: newValue)
    }
    

    If you don't want to be restricted to iOS 14 you can find additional options here: How can I run an action when a state changes?