[英]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.