SwiftUI - ForEach with Stride

空扰寡人 提交于 2020-05-16 06:32:16

问题


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]) 
            }
        } 
    }
} 

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?


回答1:


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]) 
        }

Otherwise, you may need to use stride function:

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



回答2:


For simple use-cases the solution posted by E. Coms may work. If you plan on modifying or re-ordering the list, it may give you trouble since the id specified is the same as the index and List won't be able to correctly animate removals/additions/re-ordering.

I would create a data-structure to represent the tuple in an identifiable manner:

struct SomeStructTouple: Identifiable {
  let a: SomeStruct
  let b: SomeStruct

  var id: String {
    "\(a.id)-\(b.id)"
  }
}

and then create an array of touples to generate the list.



来源:https://stackoverflow.com/questions/59548909/swiftui-foreach-with-stride

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!