TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Create a two-column grid using ForEach with variable-length array

Forums > SwiftUI

I'm trying to use Grid() to create a two-column Image() layout using ForEach, with a array of objects passed into the ForEach which has different lengths each time.

However, I'm having trouble wrapping my mind around the concept of doing this within a GridRow() item. The Issue is that ForEach only returns one item per iteration, which creates a new row for each. I've considered using something where I index the array and look at the next item to render it in that same GridRow, but that seems sloppy and clunky. Am I approaching this incorrectly?

I'm looking to achieve something like this:

Image preview

2      

Use a LazyVGrid, which will start in the top left and fill items horizontally in a row until it can't fit any more, then will wrap down to a second row, etc. You wouls just loop through your items with one ForEach and SwiftUI will take care of laying out the grid for you.

2      

The screenshot above does use a LazyVGrid, but I'm trying to move away from that because of many issues I'm having with it, the main one being:

It's very difficult and time consuming to save and resume scroll state

I'd prefer the eager gris so I can have a absolute size I can scroll to to restore the user's place in the scroll when they navigate away from the view and/or app

2      

I agree, there should be a way to do this using the new Grid(), rather than a Lazy grid. But what's the best way of laying out the objects without keeping a pointer to which object is next?

   

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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

Reply to this topic…

You need to create an account or log in to reply.

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.