SwiftUI: action while pressing a button

半腔热情 提交于 2021-02-08 05:14:55

问题


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)?

What I’m looking for is a button that:

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

回答1:


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


来源:https://stackoverflow.com/questions/61722327/swiftui-action-while-pressing-a-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!