UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

LazyVGrid update gives wrong scroll position upon switching between different grid layouts

Forums > SwiftUI

I'm trying to build a photo app that displays a collection of coffee photos. The app provides a feature for users to change the layout. By default, it shows the list of photos in a single column. The user can tap at Grid button (in appbar) to change the list view to a grid view with 2 columns. But in the process of switching from single column to 2 column the app always loses the scroll position. For ex. if I am on 7th image of coffee on single column view and when I tap grid button for 2 column view, it jumps over to the 15th and 16th image of the coffee.Please check the gif for more clarification. My question is how to maintain a scroll offset?

2      

It is keeping the same offset, it's just that each row has 2x as many pictures. So the scroll position that had image #7 at the top now has image #14 at the top when you double them up.

If you want to maintain the same image at the top regardless of how many columns are being displayed, you need to use a ScrollViewReader (iOS 14+) and explicitly set the value when you switch layouts. See this page for guidance: How to make a scroll view move to a location using ScrollViewReader

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.