0

Is it possible to have some kind of "brick" layout in SwiftUI with a different number of items in each row? Something that would satisfy the following:

  • Have the system add as many item in row 1 before moving to row 2, etc.
  • The items length are only known at runtime
  • The best example I can think of is how text work, each word is different in length and only the right number of works is displayed in each row!

I searched around stack overflow and other forums / websites but haven't found anything promising yet. Thanks for your help on this!

Slamit
  • 465
  • 1
  • 6
  • 21
  • You can try to look into this package, and get some inspiration from it https://github.com/dkk/WrappingHStack – cedricbahirwe Jun 10 '21 at 10:05
  • You can also look into this question, it's somehow similar, https://stackoverflow.com/questions/67650216/swiftui-wrapping-hstack-with-images/67651075#67651075 – cedricbahirwe Jun 10 '21 at 10:07
  • Thank you for this comment @cedricbahirwe, it seems that this is a good direction to investigate! – Slamit Jun 10 '21 at 16:25

1 Answers1

1

If I understood correctly you would need something that mimics the CollectionView:

public extension Array {

func chunked(size: Int) -> [[Element]] {
    guard size > 0 else {
        return [self]
    }
    return stride(from: 0, to: count, by: size).map {
        Array(self[$0 ..< Swift.min($0 + size, count)])
    }
}

}

and use it on a View:

ForEach(groupImages.chunked(size: rowItemCount), id: \.self) { row in
        HStack(spacing: -15) {
            renderThumbnailsRow(groupImages: groupImages, row: row)

            Spacer()
        }
}
Stefan
  • 1,283
  • 15
  • 33
  • From what I have found so far CollectionView or what you share would not work with item length being known different at runtime and different item numbers par line. rowItemCount is not known value in my case :( – Slamit Jun 10 '21 at 16:28