TabView changes selection even with empty custom handler

Viewed 91

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)
            }
        }
    }
}
0 Answers
Related