簡體   English   中英

onTapGesture 后偏移不會重置 - SwiftUI

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM