[英]Offset doesn't reset after onTapGesture - SwiftUI
我試圖創建一張卡片,當它被點擊時會滑動,然后回到原來的 position 而不再次點擊 the.onEnded() function 的點擊手勢不起作用
這是測試代碼
struct ContentView: View {
@State var tapped = false
var body: some View {
VStack {
ZStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Rectangle()
.fill(Color.red)
.frame(width: 290, height: 64)
.offset(y: tapped ? 118 : 0)
.onTapGesture {
self.tapped.toggle()
}
.animation(.easeInOut)
}
Spacer()
}.edgesIgnoringSafeArea(.all)
}
}
應用的屬性不會自行神奇地重置 - 您需要根據需要更改它們。
這是最簡單的解決方案。 使用 Xcode 11.4 / iOS 13.4 測試
var body: some View {
VStack {
ZStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Rectangle()
.fill(Color.red)
.frame(width: 290, height: 64)
.offset(y: tapped ? 118 : 0)
.onTapGesture {
self.tapped.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.tapped.toggle()
}
}
.animation(Animation.easeInOut(duration: 0.5))
}
Spacer()
}.edgesIgnoringSafeArea(.all)
}
使用顯式 animation 中的延遲解決了它。 重復循環允許您指定矩形將被反彈多少次:
struct ContentView: View {
@State var tapped = false
@State var countOfBounce: Double = 0
@State var addDelay: Double = 0
var body: some View {
VStack {
ZStack {
Rectangle()
.fill(Color.green)
.frame(height: 300)
Rectangle()
.fill(Color.red)
.frame(width: 290, height: 64)
.offset(y: tapped ? 118 : 0)
.onTapGesture {
repeat {
withAnimation(.linear(duration: 0.5).delay(0 + addDelay)){
self.tapped.toggle()
}
countOfBounce += 1
addDelay += 0.5
} while countOfBounce < 2
countOfBounce = 0
addDelay = 0
}
}
Spacer()
}.edgesIgnoringSafeArea(.all)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.