Home > Back-end >  SwiftUI ForEach index jump by 2
SwiftUI ForEach index jump by 2

Time:04-04

I am working on SwiftUI ForEach. Blow image shows what I want to achieve. For this purpose I need next two elements of array in single iteration, so that I can show two card in single go. I search on a lot but did find any way to jump index swiftUI ForEach.

need to show two cards in single iteration

Here is my code in which I have added the element same array for both card which needs to be in sequence.

    ScrollView(.vertical, showsIndicators: false) {
                VStack(spacing: 0) {
                    // I need jump of 2 indexes
                    ForEach(videos) { video in
// need to show the next two elements of the videos array
                        HStack {
                            videoCardView(video: video)
                            Spacer()
                            // video   1
                            videoCardView(video: video)
                        }
                        .padding([.leading, .trailing], 30)
                        .padding([.top, .bottom], 10)

                    }
                }
            }
            .background(Color(ColorName.appBlack.rawValue))
        }

Any better suggestion how to build this view.

CodePudding user response:

While LazyVGrid is probably the best solution for what you want to accomplish, it doesn't actually answer your question.

To "jump" an index is usually referred to as "stepping" in many programming languages, and in Swift it's called "striding".

You can stride (jump) an array by 2 like this:

ForEach(Array(stride(from: 0, to: array.count, by: 2)), id: \.self) { index in
    // ...
}

You can learn more by taking a look at the Strideable protocol.

  • Related