In SwiftUI, where are the control events, i.e. scrollViewDidScroll to detect the bottom of list data

后端 未结 5 1798
南笙
南笙 2020-12-09 18:57

In SwiftUI, does anyone know where are the control events such as scrollViewDidScroll to detect when a user reaches the bottom of a list causing an event to retrieve additio

5条回答
  •  再見小時候
    2020-12-09 19:40

    In case you need more precise info on how for the scrollView or list has been scrolled, you could use the following extension as a workaround:

    extension View {
    
        func onFrameChange(_ frameHandler: @escaping (CGRect)->(), 
                        enabled isEnabled: Bool = true) -> some View {
    
            guard isEnabled else { return AnyView(self) }
    
            return AnyView(self.background(GeometryReader { (geometry: GeometryProxy) in
    
                Color.clear.beforeReturn {
    
                    frameHandler(geometry.frame(in: .global))
                }
            }))
        }
    
        private func beforeReturn(_ onBeforeReturn: ()->()) -> Self {
            onBeforeReturn()
            return self
        }
    }
    

    The way you can leverage the changed frame like this:

    struct ContentView: View {
    
        var body: some View {
    
            ScrollView {
    
                ForEach(0..<100) { number in
    
                    Text("\(number)").onFrameChange({ (frame) in
    
                        print("Origin is now \(frame.origin)")
    
                    }, enabled: number == 0)
                }
            }
        }
    }
    

    The onFrameChange closure will be called while scrolling. Using a different color than clear might result in better performance.

    edit: I've improved the code a little bit by getting the frame outside of the beforeReturn closure. This helps in the cases where the geometryProxy is not available within that closure.

提交回复
热议问题