Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScrollViewReader scrollTo with .center anchor bug?

So I'm try to use ScrollViewReader to programmatically scroll a horizontal scroll view. I thought it would work like scrollToItem with .centeredHorizontally in UIKit, and for the most part it does, but the last few elements in the scroll view are being forcefully scrolled to the center of the screen, despite the fact that the scroll view isn't normally able to scroll that far over (without snapping back after releasing the drag, at least). This ends up creating white space across the trailing half of the screen.

I've seen some other questions about this and it seems like the general opinion is that it's not a bug? On the one hand I suppose we're telling the scroll view to center the item, and it's doing just that -- so, not a bug? On the other hand, that's not how similar functionality worked in UIKit. Also, this behavior is only happening on the trailing end of the scroll view! If it was the intended behavior I would expect that scrolling to the first element in the scroll view using .center anchor would force it into the center of the screen and leave leading white space, but this doesn't happen.

Is there an elegant solution to this? Or do we have to calculate the width of our elements + spacing and figure out based on the screen width whether we should anchor .center or just scroll to the last element with anchor .trailing in order to replicate the UIKit behavior?

like image 791
user1877760 Avatar asked Mar 01 '26 22:03

user1877760


2 Answers

I can confirm this behavior and think it should be considered a bug. Especially since the scroll view will "jump" into position on the first touch event.

As of iOS 15.4 Beta 1 this is fixed for me. Maybe give it another try.

like image 92
Stefan Wichmann Avatar answered Mar 03 '26 11:03

Stefan Wichmann


I experienced the same issue when using scrollTo with a non-nil anchor such as .center for content that has padding in a ScrollView, and was able to find a workaround:

I wanted my ScrollView to contain a VStack containing several elements, where I could scroll to each element using ScrollViewReader. However, when I applied horizontal padding to the VStack, I experienced the above bug.

When I applied horizontal padding to the individual elements of the VStack instead of to the VStack itself, the bug seems to have resolved itself.

Now, when using scrollTo("someId"), the scroll position does not have a wonky horizontal offset equal to the padding of the ScrollView's content!

like image 34
jcolicchio Avatar answered Mar 03 '26 11:03

jcolicchio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!