开发者

Incrementing two different sized arrays with different indexes in SwiftUI ForEach

let's say I have 2 arrays:

I'm looping through all the elements in array1 like so

@State var array2Index

ForEach(0 ..< array1.count, idL \.self){index in

  SomeView(varName: array1[index])

//here I want to show a different view with array2 for every second item of array1

  if index % 2 == 0{
   OtherView(varName: array2[array2Index])
   //this is not possible however
   array2Index += 1
  }

I tried to create a function that returns a View with an incremented index for array2 but it increments before the main view is even displayed because "array2Index" is a @State variable


You don't need another variable. Just do math with index:

struct SomeView: View {
    let varName: String
    
    var body: some View {
        Text(varName)
    }
}

struct OtherView: View {
    let varName: String
    
    var body: some View {
        Text(varName)
    }
}

struct ContentView: View {
    let array1 = ["Apple", "Banana", "Carrot", "Donut", "Egg"]
    let array2 = ["1", "2", "3"]

    var body: some View {
        ForEach(array1.indices, id: \.self) { index in
            
            SomeView(varName: array1[index])
            
            //here I want to show a different view with array2 for every second item of array1
            
            if index % 2 == 0 {
                OtherView(varName: array2[index / 2])
            }
        }
    }
}

Incrementing two different sized arrays with different indexes in SwiftUI ForEach

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜