I’m trying to implement scroll tracking using scrollTargetLayout in SwiftUI. My code works as expected when I use LazyHStack, but it doesn’t track the scroll position with a regular HStack.
Basically, I’ve noticed that my views don’t always load properly when paging with the LazyHStack, but they appear fine with HStack.
Here’s an example:
struct ContentView: View {
@State var pageId: Int?
var body: some View {
ZStack {
ScrollView(.horizontal) {
LazyHStack(spacing: 0) {
ForEach(1..<5) { item in
Circle()
.foregroundStyle(.red)
.containerRelativeFrame(.horizontal, count: 1, spacing: 0)
.id(item)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.scrollPosition(id: $pageId)
Text("(pageId ?? 0)")
.font(.largeTitle)
}
}
}