Last active
July 14, 2024 20:25
-
-
Save khanlou/112cbb13ee2c776aa343bfc204f78259 to your computer and use it in GitHub Desktop.
This ScrollView has a modifier called `onScroll`, which is updated when scrolls occur.
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
struct ContentView: View { | |
@State var scrollOffset: CGPoint = .zero | |
var body: some View { | |
ObservableScrollView { | |
Text("Hello, world!") | |
.foregroundColor(self.scrollOffset.y == 0 ? .blue : .red) | |
} | |
.onScroll { self.scrollOffset = $0 } | |
} | |
} |
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
struct ScrollOffsetPreferenceKey: PreferenceKey { | |
typealias Value = CGPoint | |
static var defaultValue = CGPoint.zero | |
static func reduce(value: inout CGPoint, nextValue: () -> CGPoint) { | |
value = nextValue() | |
} | |
} | |
struct ObservableScrollView<Content> : View where Content : View { | |
var content: Content | |
var axes: Axis.Set | |
var showsIndicators: Bool | |
init(_ axes: Axis.Set = .vertical, showsIndicators: Bool = true, @ViewBuilder content: () -> Content) { | |
self.content = content() | |
self.axes = axes | |
self.showsIndicators = showsIndicators | |
} | |
var body: some View { | |
GeometryReader { outerGeometry in | |
ScrollView(self.axes, showsIndicators: self.showsIndicators) { | |
ZStack(alignment: self.axes == .vertical ? .top : .leading) { | |
GeometryReader { innerGeometry in | |
Color.clear | |
.preference(key: ScrollOffsetPreferenceKey.self, value: CGPoint(x: (outerGeometry.frame(in: .global).minX - innerGeometry.frame(in: .global).minX), y: (outerGeometry.frame(in: .global).minY - innerGeometry.frame(in: .global).minY))) | |
} | |
VStack { | |
self.content | |
} | |
} | |
} | |
} | |
} | |
} | |
extension ObservableScrollView { | |
func onScroll(_ onScroll: @escaping (CGPoint) -> ()) -> some View { | |
self.onPreferenceChange(ScrollOffsetPreferenceKey.self, perform: onScroll) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrong implementation of reduce func. Closure will not called.