SwiftUI ScrollView scroll to position of a specific view’s location

To programmatically scroll to a specific position within a ScrollView, SwiftUI provides the ScrollViewReader and scrollTo method.

  1. ScrollViewReader: The ScrollViewReader is a container view that allows us to read the current position of the ScrollView and manipulate it programmatically.
  2. scrollTo Method: The scrollTo() method is used to scroll to a specific position within the ScrollView. It takes two parameters: the ID of the view to scroll to and an anchor point for the scroll position.

Now, let’s walk through the process of using ScrollView to scroll to the position of a specific view in SwiftUI:

  1. Create a ScrollView: Begin by creating a ScrollView container in your SwiftUI view. This ScrollView will hold the content that you want to scroll through.
  2. Add Content to ScrollView: Populate the ScrollView with the content you want to display. This content can be any SwiftUI view or a combination of views.
  3. Assign Unique IDs: Each view inside the ScrollView must have a unique identifier. Use the id modifier to assign a unique ID to each view. These IDs will be used to identify the views when scrolling.
  4. Use ScrollViewReader: Wrap your ScrollView content within a ScrollViewReader. This allows you to access the ScrollView’s functionality and manipulate its scroll position.
  5. Trigger Scroll Action: To scroll to a specific position, use the scrollTo method provided by ScrollViewReader. Pass the ID of the view you want to scroll to as well as an anchor point for the scroll position.

Here’s a basic example demonstrating how to use ScrollView to scroll to the position of a specific view in SwiftUI:

In this example I have added 29 views inside the scrollview with respective id of each view. So I can pass that id to the scrollTo() method to scroll to the specific view. I am using button click for scrolling to View 10. Also I have changed the changed the background colour of view 10 to green. When I tap on the button it jumps to the view 10 but it position it at bottom of screen.

I will pass second parameter anchor with value .top to show it at the top of screen.

Instead of sudden jump to view 10, I want to scroll it with animation. For this purpose I can place the scrollTo() method inside withAnimation() for smooth scrolling animation.

In this tutorial you saw how SwiftUI ScrollView scroll to position of a specific view using ScrollViewReader. You can simply embed scrolling content inside the ScrollViewReader and use the scrollTo() method to scroll to the location of a specific view by providing its unique assigned id. You can also change placement of scrolled view by providing anchor parameter. And at the end you learned that how you can make scrolling smooth using withAnimation().