0

I am trying to make an infinite scroll calling the different pages of an api, my problem is that the function onAppear is called before the view is displayed, then it is called to reload when the screen opens and not when you scroll to the bottom, I do not know if it is a problem of my Xcode or what, even with this simple code it happens to me:

struct ContentView: View {
        var body: some View {
            ScrollView {
                VStack {
                    ForEach(1...120, id: \.self) { index in
                        Text("Item \(index)")
                            .onAppear {
                                if index == 120 {
                                    print("End reached")
                                }
                            }
                    }
                }
            }
        }
}

I have tried to make a paginated view with many tutorials on the internet, not only with examples on StackOverflow and as far as I can see this is how it should be done but it doesn't work for me.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • .onAppear is viewDidAppear, but viewWillAppear. – Abhilash Jun 15 '23 at 19:09
  • Plus you are adding Texts into scroll view so they are created and added, its not working on dequeuing principle – Abhilash Jun 15 '23 at 19:16
  • @Abhilash So, how can I call the next page when the scrollView reach the bottom to have an infinite pagination? – Gonzalo MR Jun 15 '23 at 19:45
  • it is called when the `View` appears in the stack and this isn't necessarily when it becomes visible to the user. There is a certain amount of preloading that is done so the user isn't waiting for screens to load. There is no built in way to detect when a view is visible but you can use a combination of `PreferenceKey` and `GeometryReader` to detect when it is visible, just search SO for posts that relate to this topic and detecting the position of a `View` – lorem ipsum Jun 15 '23 at 19:57
  • 1
    try ScrollView, LazyVStack and onAppear combination. You can find multiple articles online – Abhilash Jun 16 '23 at 17:08
  • @Abhilash that works! My problem was with the ScrollView position and also with the VStack calling onAppear only when the data is loaded and not when the view appears, in the other hand LazyVStack calls onAppear every time the view appears on the screen, I'm learning SwiftUI so, trial and error! Thanks! – Gonzalo MR Jun 17 '23 at 00:02

0 Answers0