[英]SwiftUI Transition not working with Array of Views
我有这个简单的视图,它采用一组视图。 这个想法是点击可见视图将下一个视图滑动到位。 如果我用常量索引我的 Views 数组,这工作正常,但如果索引是 @State var 则不起作用。
这是不起作用的:
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
}
}
}
}
}
但是这个版本的body
确实有效但没有用:
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
语句而只使用pages[self.currentImage]
转换不起作用。
你会像这样使用这个视图:
ImageCarousel([
Rectangle().foregroundColor(.red),
Rectangle().foregroundColor(.orange),
Rectangle().foregroundColor(.yellow),
Rectangle().foregroundColor(.green),
Rectangle().foregroundColor(.blue),
Rectangle().foregroundColor(.purple)
])
非常感谢任何见解。 我觉得这是我没有看到的显而易见的事情。
我想出了一个不太复杂的解决方案(更多的是 hack):暂时用虚拟View
替换当前View
,当它出现时,触发下一个View
出现。 这满足删除View
并将其替换为另一个View
的条件:
var body: some View {
ZStack {
if self.currentImage == -1 {
Rectangle()
.foregroundColor(.gray)
.onAppear {
self.currentImage = self.nextImage
}
} else {
pages[self.nextImage]
.transition(.slide)
.animation(.easeInOut)
.onTapGesture {
withAnimation {
self.nextImage = self.nextImage+1 >= self.pages.count ? 0 : self.nextImage+1
self.currentImage = -1
}
}
}
}
}
这适用于这个简化的案例。 如果不需要的话,我真的不想将 go 变成UIScrollView
或UIPageViewController
领域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.