how do I track scroll position in swiftui

Asked on 08/02/2024

1 search

To track scroll position in SwiftUI, you can use the new onScrollVisibilityChange and onScrollGeometryChange modifiers introduced in the latest updates. These modifiers allow you to react to changes in the scroll view's content and visibility.

For example, the onScrollVisibilityChange modifier can be used to detect when a view's visibility changes due to scrolling. This can be useful for creating experiences centered around content moving on or off the screen. Here's a brief overview from the session "What’s new in SwiftUI":

"You can now detect when a view's visibility has changed due to scrolling, letting you create great experiences centered around content moving on or off screen like this auto-playing video."

Additionally, the onScrollGeometryChange modifier lets you performantly react to changes in the scroll view's content, offsets, content size, and more. This is demonstrated in the same session:

"You can now have a deeper level of integration with the state of a scroll view with onScrollGeometryChange which lets you performantly react to changes in things like content, offsets, content size, and more."

For a practical example, you can refer to the session "Migrate your TVML app to SwiftUI", where the onScrollVisibilityChange modifier is used to change the state when a header view moves off-screen.

To learn more about these new scroll view modifiers, you can also check out the session "Create custom visual effects with SwiftUI", which explores how to use the scrollTransition modifier to create custom scroll effects.

Relevant Sessions:

  1. What’s new in SwiftUI
  2. Migrate your TVML app to SwiftUI
  3. Create custom visual effects with SwiftUI