SwiftUI:按下按钮时执行操作

3
我正在试图实现一个长按按钮,只有在我按下按钮时才会更改我使用的 SF Symbol。我不确定应该在哪里使用这些图片。问题是当我停止按下时,按钮就被触发了。有没有办法不激活它(除非按下)?
我要实现的是一个按钮:
当按下2秒钟后,符号更改,并且在这2秒后,当释放时,符号返回到初始状态。
struct heartButton: View {

@State private var isDetectingPress = false

var body: some View {
    VStack {
        Image(systemName: isDetectingPress ? "heart.fill" : "heart").font(.system(size: 16, weight: .regular))
        Button(action: {
            self.isDetectingPress.toggle()
        }) {
            Text("Button")
        }
    }
}
1个回答

2
这里有一个解决方案。使用Xcode 11.5b测试过。 演示
struct heartButton: View {

    @GestureState private var isDetectingPress = false

    var body: some View {
        VStack {
            Image(systemName: isDetectingPress ? "heart.fill" : "heart").font(.system(size: 16, weight: .regular))
            Text("Press")
            .gesture(LongPressGesture(minimumDuration: 2).sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .local)).updating($isDetectingPress) { value, state, _ in
                    switch value {
                        case .second(true, nil):
                            state = true
                        default:
                            break
                    }
            })
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接