ScrollView with a LazyVStack with Section does not respect initial scroll position

I have a ScrollView with a LazyVStack with Sections. I initialize the ScrollView with a scroll position but the ScrollView starts with the first row at the top.

Am I doing something wrong or is this just a bug in ScrollView?

It seems to work fine if I do not use Section.

struct ContentView: View {
  @State var scrollPosition: ScrollPosition
  
  init() {
    var p = ScrollPosition(idType: Int.self)
    p.scrollTo(id: 500, anchor: .top)
    scrollPosition = p
  }
  
  var body: some View {
    ScrollView {
      LazyVStack {
        ForEach(0..<sectionCount, id: \.self) { j in
          Section {
            ForEach(0..<rowCount, id: \.self) { i in
              RowView(text: "\(j)/\(i) [\(j*rowCount+i)]")
                .id(j*rowCount+i)
            }
          } header: {
            HeaderView(title: "\(j)")
          }
        }
      }
      .scrollTargetLayout()
    }
    .scrollPosition($scrollPosition)
  }
}

Are you able to share the RowView and HeaderView you are using?

When I try this code, removing the Section doesn't make a difference. Are you able to simplify those views in a way that still reproduces the issue? I want to make sure it's not the way those views are defined.

Since we are scrolling to content in a LazyVStack, consider: views that are off screen may be deallocated to achieve better performance. Lazy containers estimate the total content size and only render views as they approach the visible area — so I have a feeling at the same moment the system is interpreting the initial scroll position, the target view may still be in the process of being laid out or may not have been created yet, causing a race condition.

We go in-depth into Lazy Stacks with Dive into lazy stacks and scrolling with SwiftUI from WWDC26, check out that session as there's tons of great info on a lazy stacks, which are useful in almost every project.

 Travis

ScrollView with a LazyVStack with Section does not respect initial scroll position
 
 
Q