![]() ![]() That’s where our good old friend GeometryReader comes in (wouldn’t be a proper SwiftUI layout workaround without it, right?). So if we can find a way to observe the frame of that container, then we’ll essentially have found a way to observe the scroll view’s content offset. They then clip that container to their bounds to produce the illusion of the viewport moving. One thing that’s key to realize before we begin is that both UIScrollView and SwiftUI’s ScrollView perform their scrolling by offsetting a container that’s hosting our actual scrollable content. So, let’s instead see if we can find a completely SwiftUI-native way to perform such content offset observations. Not impossibly by any means, but still, a fair bit of additional work and complexity. So if we wanted to build a custom, observable version of ScrollView using UIScrollView, then we’d have to wrap that implementation in a view controller, and then manage the relationship between our UIHostingController and things like the keyboard, the scroll view’s content size, safe area insets, and so on. ![]() That’s mainly because - at least on iOS - we can only embed SwiftUI content within a UIHostingController, not within a self-managed UIView. However, even though I’m normally a big fan of using UIViewRepresentable and the other SwiftUI/UIKit interoperability mechanisms, in this case, we’d have to write quite a bit of extra code to bridge the gap between the two frameworks. One way to solve that problem would be to utilize the rich capabilities of UIKit’s UIScrollView, which - thanks to its delegate protocol and the scrollViewDidScroll method - provides an easy way to get notified whenever any kind of scrolling occurred. While embedding a ScrollViewReader within a scroll view does enable us to change the scroll position in code, it strangely (especially given its name) doesn’t let us read the current content offset in any way. However, when it comes to SwiftUI’s ScrollView, there’s currently (at the time of writing) no built-in way to perform such scrolling observations. When building various kinds of scrollable UIs, it’s very common to want to observe the current scroll position (or content offset, as UIScrollView calls it) in order to trigger layout changes, load additional data when needed, or to perform other kinds of actions depending on what content that the user is currently viewing.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |