繁体   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