whats the difference between ScrollViewReader and ScrollProxy

Generated on 8/2/2024

1 search

The difference between ScrollViewReader and ScrollProxy in SwiftUI is primarily about their roles and how they are used to control scroll views.

  1. ScrollViewReader:

    • ScrollViewReader is a view that provides a ScrollProxy to its content. It allows you to programmatically control the scroll position of a ScrollView.
    • You wrap your ScrollView inside a ScrollViewReader and use the ScrollProxy provided by the ScrollViewReader to scroll to specific positions or items.
    • Example usage:
      ScrollViewReader { proxy in
          ScrollView {
              ForEach(0..<100) { index in
                  Text("Item \(index)")
                      .id(index) // Assign an ID to each item
              }
          }
          .onAppear {
              proxy.scrollTo(50) // Scroll to item with ID 50
          }
      }
      
  2. ScrollProxy:

    • ScrollProxy is the object provided by ScrollViewReader that you use to perform the actual scrolling actions.
    • It provides methods like scrollTo(_:anchor:) to scroll to a specific view identified by an ID.
    • The ScrollProxy is what gives you the programmatic control over the scroll view's content.

In summary, ScrollViewReader is the container that provides a ScrollProxy, and ScrollProxy is the tool you use to control the scroll position within the ScrollView.

For more detailed information on scroll view enhancements in SwiftUI, you can refer to the session What’s new in SwiftUI.