How to set the scroll position in a LazyHStack in SwiftUI
Emily Wong
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)") } } } } }
}Automatic scroll
struct ContentView: View { var body: some View { ScrollViewReader { value in ScrollView(.horizontal) { LazyHStack(alignment: .top, spacing: 10) { ForEach(1...100, id: \.self) { Text("Column \($0)") } } } .onAppear { value.scrollTo(15, anchor: .center) } } }
} 2