let's say I have 2 arrays:
- array1开发者_运维百科.count = 5
- array2.count = 3
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])
}
}
}
}
精彩评论