Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 725
Daniele B Avatar asked Dec 01 '25 10:12

Daniele B


1 Answers

The above answers work well except in one condition. If you are present in the same tab .onChange() won't be called. the better way is by creating an extension to binding

extension Binding {
    func onUpdate(_ closure: @escaping () -> Void) -> Binding<Value> {
        Binding(get: {
            wrappedValue
        }, set: { newValue in
            wrappedValue = newValue
            closure()
        })
    }
}

the usage will be like this

TabView(selection: $selectedTab.onUpdate{ model.myFunction(item: selectedTab) }) {
        Text("Graphs").tabItem{Text("Graphs")}
           .tag(1)
        Text("Days").tabItem{Text("Days")}
           .tag(2)
        Text("Summary").tabItem{Text("Summary")}
           .tag(3)
    }
like image 183
veeresh ks Avatar answered Dec 04 '25 02:12

veeresh ks