Just published my first Swift article of 2023! 🎉

This one is about how the content offset (or scroll position) of a SwiftUI ScrollView can be observed without requiring any UIKit bridging. Very useful when implementing things like collapsable headers, or when performing other kinds of scroll position-dependent operations 👍

https://www.swiftbysundell.com/articles/observing-swiftui-scrollview-content-offset

Observing the content offset of a SwiftUI ScrollView | Swift by Sundell

How the content offset of a SwiftUI ScrollView can be observed without bridging to UIKit.

Swift by Sundell
@johnsundell This is really helpful, thanks so much! Looking forward to playing with it.
@majelbstoat Cheers, glad you’re finding the article useful 🙂

@johnsundell so, in playing around with it, this didn’t actually work for me until I removed value = nextValue().

I don’t understand why, and it’s possible I was doing something wrong in the downstream usage, but nextValue was always generating a zero (and the inout value was already the correct number).

@majelbstoat Mind sharing your code with me as a Gist or something? Would be happy to take a look to figure out what’s going on 🙂

@johnsundell sure thing 🙂

https://gist.github.com/majelbstoat/88dcdd95ab493677ff789d827daf366f

It’s essentially your exact code, replacing gradients for solid colors, and commenting out that line.

The Preview in the second file should demonstrate the behavioral difference.

CollapsibleHeaderView.swift

GitHub Gist: instantly share code, notes, and snippets.

Gist
@majelbstoat Seems to be a preview bug. Also can’t make it work in when using a preview, but your code runs as expected in the simulator. In general, I’d advise against using previews to build these kinds of interactions, and only use them when developing individual components. It’s very common to run into these kinds of issues otherwise.
@johnsundell @majelbstoat I ran into this exact same issue in the simulator as well, and it only started working when I removed the reduce