I want to have a ScrollView where you can be aware of the content frame changes as the user scrolls (similar to didScroll delegate in UIKit UIScrollView).
With this, you can then perform layout changes based on the scroll behavior.
I want to have a ScrollView where you can be aware of the content frame changes as the user scrolls (similar to didScroll delegate in UIKit UIScrollView).
With this, you can then perform layout changes based on the scroll behavior.
Maciek Czarnik
On
There is an elegant solution to this problem, Soroush Khanlou already posted a Gist of it so I won't copy-paste it. You can find it here and yeah...Shame that it isn't a part of the framework yet!
Copyright © 2021 Jogjafile Inc.
I managed to come with a nice solution for this problem by making use of View Preferences as a method to notify layout information upstream in the View Hierarchy.
For a very detail explanation of how View Preferences work, I will suggest reading this 3 articles series on the topic by kontiki
For my solution, I implemented two
ViewModifiers: one to make a view report changes on its layout using anchor preferences, and the second to allow aViewto handle updates to frames on views on its subtree.To do this, we first define a
Structto carry the identifiable frame information upstream:and we define a
Structconforming toPreferenceKeyprotocol to hold the view tree preference changes:Now we can define the
ViewModifiersI mentioned:Make a view report changes on its layout:
This just adds a
transformAnchorPreferencemodifier to the View with a handler that simply constructs aViewFrameinstance with current frameAnchorvalue and appends it to the current value of theFramePreferenceKey:Provide an update handler to a view for frame changes on its subtree:
This adds a
onPreferenceChangemodifier to the View, where the list of frame Anchors changes are transformed into frames(CGRect) on the view's coordinate space and reported as a dictionary of frame updates keyed by the view ids:LET'S USE IT:
I will illustrate the usage with an example:
Here I will get notifications of a Header View frame changes inside a
ScrollView. Since this Header View is on the top of theScrollViewcontent, the reported frame changes on the frame origin are equivalent to thecontentOffsetchanges of theScrollView