SwiftUI: how to handle BOTH tap & long press of button?

感情迁移 提交于 2019-12-22 10:49:04

问题


I have a button in SwiftUI and I would like to be able to have a different action for "tap button" (normal click/tap) and "long press".

Is that possible in SwiftUI?

Here is the simple code for the button I have now (handles only the "normal" tap/touch case).

Button(action: {self.BLEinfo.startScan() }) {
                        Text("Scan")
                    } .disabled(self.BLEinfo.isScanning)

I already tried to add a "longPress gesture" but it still only "executes" the "normal/short" click. This was the code I tried:

Button(action: {self.BLEinfo.startScan() }) {
                        Text("Scan")
                            .fontWeight(.regular)
                            .font(.body)
                        .gesture(
                            LongPressGesture(minimumDuration: 2)
                                .onEnded { _ in
                                    print("Pressed!")
                            }
                        )
                    }

Thanks!

Gerard


回答1:


I tried many things but finally I did something like this:

    Button(action: {
    }) {
        VStack {
            Image(self.imageName)
                .resizable()
                .onTapGesture {
                    self.action(false)
                }
                .onLongPressGesture(minimumDuration: 0.1) {
                    self.action(true)
                }
        }
    }

It is still a button with effects but short and long press are different.




回答2:


This isn't tested, but you can try to add a LongPressGesture to your button.

It'll presumably look something like this.

struct ContentView: View {
    @GestureState var isLongPressed = false

    var body: some View {
        let longPress = LongPressGesture()
            .updating($isLongPressed) { value, state, transaction in
                state = value
            }

        return Button(/*...*/)
            .gesture(longPress)
    }
}


来源:https://stackoverflow.com/questions/58284994/swiftui-how-to-handle-both-tap-long-press-of-button

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