How do I run a function when TabView tab is changed

Viewed 316

I've tried many different ways but none of them work, and im getting this error when I try to add .onChange

Instance method 'onChange(of:perform:)' requires that 'Binding<Int>' conform to 'Equatable'

I defined currentTab like this

@State var currentTab = 0;

This code gives the error

.onChange(of: $currentTab, perform: { newValue in
    print(newValue)
})
2 Answers

The onChange modifier requires value of state, not binding, so just remove $, like

.onChange(of: currentTab) { newValue in
    print(newValue)
}

for the onChange to work you need to do a bit more than just slapping a onChange, you need to include the appropriate tags, like this example

struct ContentView: View {
    @State var value: Int = 1
    
    var body: some View {
        TabView(selection: $value) {
            Text("View One").tabItem { Text("One") }.tag(1)
            Text("View Two").tabItem { Text("Two") }.tag(2)
            Text("View Three").tabItem {Text("Three") }.tag(3)
        }
        .onChange(of: value) { val in
            print("---> val: \(val)")
        }
    }
}

Note: the tag type should match the "value" type.

Related