Reading great tutorials (that use PreferenceKey), I’m able to follow the scrolling in my SwiftUI ScrollView.
For example, in a ScrollView with:
- y content size of 5000 pt
- scroll view height of 675 pt
=> the position read when I scroll to bottom of my scrollView is 4325pt (5000 – 675)
OK. Now I want to set the position of this last scroll in onAppear().
So I need to use scrollTo with an anchor point.
But Anchor Point is computed between 0 and 1 and doesn’t use an “absolute” position at the time of iOS 17.
So I need to convert the position to anchor point.
It could be something easy like that:
let anchorPoint: UnitPoint = UnitPoint(x: lastPositionX / contentWidth, y: lastPositionY / contentHeight)
scroll.scrollTo(bottomId, anchor: anchorPoint)
Problem: when I’m at bottom of the scroll for the anchor point, it’s a 1.0 value and not 0.865 (4325/5000). However, the position value corresponding to this is 5000pt in my case, and not 4325pt while 4325 is really the Y position read when I’m at bottom.
So, I think I need to adjust to convert to Anchor Point, but I didn’t match the “rule” I can use.
What I saw is when the Y position > to the half of the contentSize.height, I need to add extra offset proportionnaly to the scrollViewSize.height, like this:
let lastPositionY = scrollPosition.y + (scrollViewSize.height * (scrollPosition.y / contentSize.height))
However, this doesn’t work.
I can’t find a way to add this extra space for all scrolling scenarios (top, middle, bottom). When the scroll is at top I need to add nothing too.