Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scroll direction programmatically in SwiftUI ScrollView

I want display or hide items by scroll direction just like safari. Hide something when scroll up, and show it when scroll down.

like image 646
Candy Avatar asked Dec 15 '19 08:12

Candy


2 Answers

I think, simultaneousGesture is a better solution because it's not blocking scrollView events.

ScrollView {

}
.simultaneousGesture(
       DragGesture().onChanged({
           let isScrollDown = 0 < $0.translation.height
           print(isScrollDown)
       }))

This method only detects a new scrool if the screen has stop scrolling

like image 168
Den Avatar answered Oct 16 '22 23:10

Den


You would use GeometryReader to get the global position of one in the views in the ScrollView to detect the scroll direction. The code below will print out the current midY position. Dependent on the +/- value you could display or hide other views.

struct ContentView: View {

var body: some View {
    ScrollView{
        GeometryReader { geometry in

                Text("Top View \(geometry.frame(in: .global).midY)")
                    .frame(width: geometry.size.width, height: 50)
                    .background(Color.orange)
            }

    }.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 0, maxHeight: .infinity, alignment: .center)
}

}

like image 37
Marc T. Avatar answered Oct 17 '22 00:10

Marc T.