0

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?

TheDummy
  • 65
  • 7
  • Does this answer your question https://stackoverflow.com/a/65871577/12299030? – Asperi Feb 06 '22 at 11:05
  • @Asperi I added `.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? – TheDummy Feb 06 '22 at 11:28
  • Does [this answer](https://stackoverflow.com/a/69500827/7129318) your question? Look to the code after the edit. – Yrb Feb 06 '22 at 16:22

0 Answers0