Created
January 11, 2021 08:00
-
-
Save robhasacamera/9b0f3e06dcf27b54962ff0e077249e0d to your computer and use it in GitHub Desktop.
This file contains 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
// Modified from https://swiftuirecipes.com/blog/pull-to-refresh-with-swiftui-scrollview | |
struct OffsetAwareScrollView<Content>: View where Content: View { | |
typealias OffsetReceiver = (CGFloat) -> Void | |
let axes: Axis.Set | |
let showsIndicators: Bool | |
let offsetReceiver: OffsetReceiver | |
let content: Content | |
init(_ axes: Axis.Set = .vertical, | |
showsIndicators: Bool = true, | |
offsetReceiver: @escaping OffsetReceiver, | |
@ViewBuilder content: () -> Content) | |
{ | |
self.axes = axes | |
self.showsIndicators = showsIndicators | |
self.offsetReceiver = offsetReceiver | |
self.content = content() | |
} | |
var body: some View { | |
ScrollView(axes, showsIndicators: showsIndicators) { | |
ZStack(alignment: .top) { | |
PositionIndicator(type: .moving) | |
.frame(height: 0) | |
VStack { | |
content | |
} | |
} | |
} | |
// May have to add disabled here and override OffsetAwareScrollView disable func to also set a disabled state | |
.background(PositionIndicator(type: .fixed)) | |
.onPreferenceChange(PositionPreferenceKey.self) { values in | |
DispatchQueue.main.async { | |
let movingY = values.first { $0.type == .moving }?.y ?? 0 | |
let fixedY = values.first { $0.type == .fixed }?.y ?? 0 | |
let offset = movingY - fixedY | |
offsetReceiver(offset) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment