Why the geometryreader always prints current index 1? The expected functionality is to print the shown object id when the user scrolls. But it does not change, what could be the issue? The current index should change when user scrolls without pressing the buttons.
struct SwiftUIView: View {
{
ScrollView {
ScrollViewReader { value in
Button("Go to next") {
withAnimation {
value.scrollTo((currentIndex), anchor: .top)
currentIndex += 1
print (currentIndex)
}
}
.padding()
Button("Go to previous") {
withAnimation {
value.scrollTo((currentIndex), anchor: .top)
currentIndex -= 1
print (currentIndex)
}
}
.padding()
VStack {
ForEach(0..<12, id: \.self) { obj in
PostCard(message:message1)
.onAppear{
print(">> added \(obj)")
current.append(obj)
}
.onDisappear {
current.removeAll { $0 == obj }
print("<< removed \(obj)")
}.id(obj)
}
}
.background(GeometryReader {
Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) {_ in
if current.count > 0 {
currentIndex = current.sorted()[1]
print("current index \(String (currentIndex))")
}
}
}
}
}
}
}
}
}
}