我们如何为ForEach SwiftUI制作自定义步骤?

时间:2020-10-23 02:33:08

标签: swiftui

我有一个适用于索引的ForEach循环,我如何使此ForEach步骤获得自定义步骤,因为在ForEach的每个循环中,它将为索引添加一个,我们如何将步骤设为5,这意味着每个循环加5代替1。我可以使用if和%来实现,但我不希望ForEach尝试Items中的每个Item。如何使它高效编码?

代码:

 struct ContentView: View
{
    var body: some View
    {
        
        
        List
        {
            ForEach(0 ..< 21) { index in // (Step == 5) not 1
                Text("Hello, world!")
                    .padding()
            }
  
        }
 

    }
}

 

1 个答案:

答案 0 :(得分:2)

这是可行的方法

List
{
    ForEach(Array(stride(from: 0, to: 21, by: 5)), id: \.self) { index in // (Step == 5) not 1
        Text("Hello, world!")
            .padding()
    }

}