SwiftUI tabview (scroll) events?

Viewed 76

Is it possible to attach a scroll change event to a TabView in SwiftUI? I'd like to get the scroll position when the user touches and drags one of the views, which gets updated on every change of the position.

    TabView {

        Text("Example 1")
        Text("Example 2")
        Text("Example 3")

    }
    .tabViewStyle(PageTabViewStyle())

I tried by adding DragGesture but then the TabView didn't work anymore (probably because the DragGesture takes over the input). I also didn't see any corresponding events in Apple's docs.

Does anyone know a way to implement this?

Cheers..

1 Answers

We can track it in different way - by changed view coordinates (actually it is almost the same as drag translation)

Here is a dome for one tab. Tested with Xcode 13.4 / iOS 15.5

var body: some View {
    TabView {

        Text("Example 1")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(GeometryReader {
                // read and store origin (min X) of page
                Color.clear.preference(key: ViewOffsetKey.self,
                    value: $0.frame(in: .global).minX)
            })

        Text("Example 2")
        Text("Example 3")

    }
    .tabViewStyle(PageTabViewStyle())
    .onPreferenceChange(ViewOffsetKey.self) {
        // process here update of page origin as needed
        print("Offset >> \($0)")
    }
}

demo

Related