Last active
June 14, 2022 17:31
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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