Home > other >  SwiftUI: Trigger event after scrolling to end of a paged tabview
SwiftUI: Trigger event after scrolling to end of a paged tabview

Time:02-02

I'm trying to have a prompt be called after a user reaches the end of a paged TabView and tries to scroll one extra. (For example, if there are three pages, once the user scrolls to the third page and tries to scroll to a fourth, it pulls up the prompt). I tried doing this:

TabView (selection: $currentIndex) {
   ...
}
.tabViewStyle(.page(indexDisplayMode: .never))
.onChange(of: currentIndex) { _ in

}

However, since the user is already on the last tab, the index isn't updated so the prompt can't be called. How can I achieve this?

CodePudding user response:

Doesn't this work for you?. It reacts after showing 1/2 of the last (dummy) view:

struct ContentView: View {
    
    @State private var currentIndex = 0
    @State private var showAlert = false
    
    let colors: [Color] = [.blue, .green, .cyan, .teal, .clear]

    var body: some View {
        
        TabView (selection: $currentIndex) {
            ForEach(0..<5) { i in
                ZStack {
                    colors[i]
                    Text("Tab \(currentIndex)")
                        .font(.title)
                }
            }
        }
        .tabViewStyle(.page(indexDisplayMode: .never))
        
        .onChange(of: currentIndex) { _ in
            if currentIndex == 4 {
                currentIndex = 3
                showAlert = true
            }
        }
        .alert("You reached the end", isPresented: $showAlert) { }
    }
}
  •  Tags:  
  • Related