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 is there any way to set the exact content offset in SwiftUI? I've been stuck with a bug where I need to restore exact scroll position, but it seems like SwiftUI may not be capable of this
@simsaens Unfortunately not, you’ll have to wrap UIScrollView for that. Using ScrollViewReader you can only scroll to a view with a specific ID, not to an exact position.
@johnsundell thank you, good to know I can stop investigating that avenue
@simsaens @johnsundell I haven’t tried yet, but what about adding hidden views for every point, give them an ID, and then use that to scroll to?
@tobiasdm @simsaens I wouldn’t recommend doing that, as that’d make your view graph significantly more complex. Consider a 3000 point tall scroll view, you’d be adding 3000 extra views just for the purpose of being able to scroll to them. At that point, I’d much rather wrap UIScrollView (which I know I said in yesterday’s article that it’s complicated to do, but it’s not *that bad*). In general, I vastly prefer using wrapped UIKit views over hacking SwiftUI.
@johnsundell @tobiasdm @simsaens and what about a single “scroll destination” view, positioned at the place where you want the scroll to be?
@emiliopelaez @johnsundell @tobiasdm in this case the user can scroll anywhere, and I want to restore that position later when they come back to that screen
@emiliopelaez @johnsundell @tobiasdm oh I think I understand, position the view where the user last left the scroll offset. Interesting!
@simsaens @emiliopelaez @tobiasdm Oh yeah, that’s a very interesting solution indeed! Would love to hear how that works out if you end up trying that 😀