Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to set the scroll position in a LazyHStack in SwiftUI

Writer 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.