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...
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
Must Read
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)")
}
}
}
}
}
}