3

The code below changes the selection variable. Why? I thought a custom handler allowed me to intercept everything. The behavior I expect is for nothing to happen when I press a tab item. But what it does is set the selection variable and change the view. What gives?

struct ContentView: View {
    @State private var selection = 0

    var handler: Binding<Int> { Binding(
        get: { selection },
        set: { log.info("I don't set the selection variable, the tab changes \($0)") }
    ) }

    var body: some View {
        ZStack {
            TabView(selection: handler) {
                Text("view 0")
                    .tabItem {
                        Label("Home", systemImage: "house.fill")
                    }.tag(0)
                Text("view 1")
                    .tabItem {
                        Label("Arrows", systemImage: "arrow.left.arrow.right")
                    }.tag(1)
                Text("view 3")
                    .tabItem {
                        Label("Arrow Up", systemImage: "arrow.up")
                    }.tag(2)
            }
        }
    }
}
Bjørn Olav Jalborg
  • 373
  • 1
  • 3
  • 14
  • SwiftUI is reactive world - handler is only a reaction on user action... and btw - `selection` variable is not changed - you print input argument of setter. Possible workaround for your scenario is here https://stackoverflow.com/a/64727573/12299030. – Asperi Jan 26 '22 at 17:23
  • That's true. The selection variable is not changed. But then why does the tab change? – Bjørn Olav Jalborg Jan 27 '22 at 08:00

0 Answers0