The following scroll view works well. It has buttons to go to next and previous Rectangles. However, the user can scroll without the buttons as well (expected functionality). Then the currentIndex
wont change, how to make the currentIndex
change according to the rectangle that the user is viewing?
var body: some View {
var currentIndex: Int = 0
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()
ForEach(0..<100) { i in
ZStack {
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200)
Text (i)
.id(i)
.onAppear{ currentIndex = i
print (currentIndex) }
}
}
}
}}
Edits:
If I add .onAppear{ currentIndex = i, print (currentIndex)
but neither it changes to the current object id and it does not get printed as well. What's the reason?