Skip to content

Instantly share code, notes, and snippets.

@tobitech
Last active June 14, 2022 17:31
Show Gist options
  • Save tobitech/a32ad6db3f2f3a2c4d790799ab62d787 to your computer and use it in GitHub Desktop.
Save tobitech/a32ad6db3f2f3a2c4d790799ab62d787 to your computer and use it in GitHub Desktop.
Implement a pull down gesture on a ScrollView to perform an action in SwiftUI. The idea is to monitor the vertical y offset of the ScrollView.
import SwiftUI
struct OverviewView: View {
private let threshold: CGFloat = 100.0
@State private var showModal = false
var body: some View {
GeometryReader { geometry in
ScrollView(showsIndicators: false) {
VStack {
}
.anchorPreference(key: OffsetPreferenceKey.self, value: .top) { anchor in
geometry[anchor].y
}
}
.onPreferenceChange(OffsetPreferenceKey.self) { offset in
if offset > threshold {
showModal = true
}
}
.sheet(isPresented: $showModal) {
PresentedView()
}
}
}
}
private struct OffsetPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat = 0.0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment