How to scroll to a specific row in a list in SwiftUI

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

If you want to programmatically scroll to a specific row in a list, you can use the scrollTo() method of the ScrollViewReader view in SwiftUI. Here’s how it works:

  1. Wrap your list in a ScrollViewReader view. This view allows you to read and manipulate the scroll position of the list.

For example, the following code creates a list of 50 rows wrapped in a ScrollViewReader:

ScrollViewReader { scrollView in
  List {
    ForEach(1...50, id: \.self) { row in
      Text("Row \(row)")
    }
  }
}
  1. Use the scrollTo() method of the ScrollViewReader to scroll to a specific row in the list. This method takes an id parameter that identifies the row to scroll to, and an optional anchor parameter that specifies where the row should be positioned within the scroll view.

For example, the following code scrolls to the 10th row and positions it at the top of the scroll view:

scrollView.scrollTo(50, anchor: .top)
  1. If you want to scroll to a specific row in response to a user action (such as a button tap), you can use the onTapGesture modifier on the button and call the scrollTo() method within the gesture’s closure.

For example, the following code creates a button that, when tapped, scrolls to the 10th row of the list:

Button("Scroll to Row 10") {
  scrollView.scrollTo(10, anchor: .top)
}


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.