SwiftUI-步步为营 [英] SwiftUI - ForEach with Stride

查看:60
本文介绍了SwiftUI-步步为营的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建Hstack卡的列表,也就是说,我想创建一系列行的滚动视图.每行将包含一个由两个视图并排显示的HStack,并由某些列表数据结构初始化.

Im trying to create a list of Hstack'd cards, That is to say, I want to create a scroll view of a series of rows. Each row would contain an HStack of two views displayed side by side, and initialized by some list data structure.

struct MyHStackView: View { 

    var myArray = [SomeStruct(1), SomeStruct(3), SomeStruct(4), SomeStruct(5), SomeStruct(6)]

    var body: some View {
        ScrollView(.vertical) { 
            VStack { 
                ForEach(0..<self.myArray.count) { index in 
                    HStack { 
                        SubView(myArray[index])
                        SubView(myArray[index+1]) 
            }
        } 
    }
} 

唯一的问题是我当前的实现涉及到数组的每个元素,新的ForEach中是否内置了 stride 函数,以便我可以对数组上的每个其他元素进行索引以初始化行?您将如何处理?

The only issue is my current implementation touches every element of the array, is there a stride function built into the new ForEach so that I can index on every other element on the array to initialize the row? How would you approach this?

推荐答案

如果只是彼此,则可以尝试

If just every other , you may try

  VStack { 
            ForEach(0 ..< self.myArray.count/2) { index in 
                HStack { 
                    SubView(myArray[index * 2])
                    SubView(myArray[index * 2 + 1]) 
        }

否则,您可能需要使用 stride 函数:

Otherwise, you may need to use stride function:

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

这篇关于SwiftUI-步步为营的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆