I have this simple View that takes an array of Views. The idea is that clicking on the visible view slides the next view into place. This is working fine if I index my Views array with constants but does not work if the index is a @State var.
This is what is NOT working:
struct ImageCarousel<Page : View>: View {
let pages:[Page]
@State private var currentImage = 0
init(_ views:[Page]) {
pages = views
}
var body: some View {
VStack {
pages[self.currentImage]
.transition(.slide)
.animation(.easeInOut)
.onTapGesture {
withAnimation {
self.currentImage = self.currentImage+1 >= self.pages.count ? 0 : self.currentImage+1
}
}
}
}
}
But this version of body
does work but is not useful:
var body: some View {
VStack {
if self.currentImage == 0 {
pages[0]
.transition(.slide)
.animation(.easeInOut)
.onTapGesture {
withAnimation {
self.currentImage = 1
}
}
} else {
pages[1]
.transition(.slide)
.animation(.easeInOut)
.onTapGesture {
withAnimation {
self.currentImage = 0
}
}
}
}
}
If I do not have the IF
statement and just use pages[self.currentImage]
the transition does not work.
You would use this View this like:
ImageCarousel([
Rectangle().foregroundColor(.red),
Rectangle().foregroundColor(.orange),
Rectangle().foregroundColor(.yellow),
Rectangle().foregroundColor(.green),
Rectangle().foregroundColor(.blue),
Rectangle().foregroundColor(.purple)
])
Any insight is greatly appreciated. I feel like this is something obvious that I am not seeing.