I'm trying to implement scroll tracking using scrollTargetLayout and scrollPosition 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 that works with HStack:
struct ContentView: View {
@State var pageId: Item.ID?
var items: [Item] = [.init(), .init(), .init(), .init()]
var body: some View {
ZStack {
ScrollView(.horizontal) {
HStack(spacing: 0) {
ForEach(items) { item in
Circle()
.foregroundStyle(.secondary)
.containerRelativeFrame(.horizontal, count: 1, spacing: 0)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.scrollPosition(id: $pageId)
if let pageId {
Text(pageId.uuidString)
.font(.caption)
}
}
}
}
However, if I try to use my own custom view it no longer works to track the scroll position:
struct CircleView: View {
var body: some View {
Circle()
}
}
struct ContentView: View {
@State var pageId: Item.ID?
var items: [Item] = [.init(), .init(), .init(), .init()]
var body: some View {
ZStack {
ScrollView(.horizontal) {
HStack(spacing: 0) {
ForEach(items) { item in
CircleView()
.foregroundStyle(.secondary)
.containerRelativeFrame(.horizontal, count: 1, spacing: 0)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.scrollPosition(id: $pageId)
if let pageId {
Text(pageId.uuidString)
.font(.caption)
}
}
}
}
idmodifier. Does that fix the issue?.idis relevant. I found that your example works when using anHStackif you change it toForEach(1..<5, id: \.self)and comment out the.idmodifier on theCircle..idmodifier seems to do the trick. Any idea why that doesn't work with HStack there?