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

Uplift iOS Interview

"Uplift iOS Interview" is a comprehensive guide to help aspiring iOS developers soar to new heights in their careers. This book is an indispensable tool for anyone looking to crack the iOS interview and impress their future employers with their technical prowess. With in-depth coverage of Swift, AutoLayout, SwiftUI, Multithreading, Memory management so on and so forth, this book is a treasure trove of knowledge for anyone looking to uplift their iOS development career.

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)
}

Rev Up Your iOS Skills: Take a Dynamic Learning Journey
iOS Career Boost

iOS Career Boost is the ultimate learning journey to elevate your iOS development career through a dynamic blend of visual learning, handy cheat sheets, coding practice materials, and expertly curated tips and tricks


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. Your email address will only be used for the purpose of sending the newsletter and will not be shared with third parties or advertisers. Rest assured that we value your privacy and will not spam your inbox.


Connect with me on

Twitter and LinkedIn and don't hesitate to reach out with any questions about this post. Thank you for reading.

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