How to Set the Scroll Position in a Lazyhstack in Swiftui

I have a horizontally scrolling LazyHStack. How do I set the initial scroll position?

In UIKit, I would create a horizontally scrolling UICollectionView and set the collectionView.contentOffset to set the initial scroll position, but I'm not sure how to do this in SwiftUI.

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack {
                ForEach(1...100, id: \.self) { i in             
                    Text("\(i)")
                }
            }
        }
    }   
}

1 Answer

You can use ScrollViewReader

Manual scroll

struct ContentView: View {
    var body: some View {
        ScrollViewReader { value in
            Button("Go to #15") {
                value.scrollTo(15, anchor: .center)
            }
            ScrollView(.horizontal) {
                LazyHStack(alignment: .top, spacing: 10) {
                    ForEach(1...100, id: \.self) {
                        Text("Column \($0)")
                    }
                }
            }
        }
    }
}
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.