SwiftUI:按下按钮时的动作 [英] SwiftUI: action while pressing a button

查看:51
本文介绍了SwiftUI:按下按钮时的动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个长按按钮,该按钮仅在我按下按钮时更改我正在使用的 SF 符号.我也不确定应该在哪里使用图像.问题是当我停止按下时,按钮被触发.有没有办法不激活它(按下时除外)?

I’m trying to implement a long press button that changes the SF Symbol that I’m using only when I’m pressing down on the button. I’m not really sure where I should use the the Images as well. The problem is that when the I stop pressing, the button is triggered. Is there a way to don’t activate it (except while pressing down)?

我正在寻找一个按钮:

按下 2 秒时,符号改变,2 秒后,当松开时,符号回到<强>初始状态.

When pressed for 2 seconds, the Symbol changes, and after those 2 seconds, when released, the Symbol go back to the initial state.

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")
        }
    }
}

推荐答案

这里有一个解决方案.使用 Xcode 11.5b 测试.

Here is a solution. Tested with 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
                    }
            })
        }
    }
}

这篇关于SwiftUI:按下按钮时的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆