for some reason the increment variable in a foreach loop doesn’t work with swiftui –

Instead of increasing index, compute the index from the row and column indices.

If your array contains 8 images and you want 2 columns, then you will have 8/2 == 4 rows. Your outer loop should loop over the number of rows which can be computed as imageArray.count/PartyCollectionViewCell.column.

Then the index of the image would be row * PartyCollectionViewCell.column + column.

func makeView() -> Text{
    return Text("App") //Return a view

ForEach(0..<(imageArray.count/PartyCollectionViewCell.column)) { row in
        ForEach(0..<PartyCollectionViewCell.column) { column in
            self.makeView() // Call the function in the content view
            PartyCollectionViewCell(cellImg: imageArray[row * PartyCollectionViewCell.column + column]!) 
        }         //update the cell
// Handle partial row
if (imageArray.count % PartyCollectionViewCell.column > 0) {
    HStack {
        ForEach((imageArray.count/PartyCollectionViewCell.column)*PartyCollectionViewCell.column..<imageArray.count) { index in
            PartyCollectionViewCell(cellImg: imageArray[index]!) 
        ForEach(0..<(PartyCollectionViewCell.column - imageArray.count % PartyCollectionViewCell.column)) { _ in

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top