简体   繁体   中英

Button with double action (tap & long press) in SwiftUI

Is it possible in SwiftUI to set a button with an action on tap and a different action on long press?

I have tried this:

Button(action: {
    self.handleButtonTap()
})
{
    Text("My nice button")
        .foregroundColor(.primary)
}
.onLongPressGesture {
    print("Long pressed!")
}

or instead of:

.onLongPressGesture {
    print("Long pressed!")
}

using this:

.gesture(longPress)

where long press is something like:

var longPress: some Gesture {
  ....
}

But nothing seems to work. At best I have been able to attach the long press gesture to the Text of the button, but even in that case the normal tap cease to work.

Any good advice will be highly appreciated.

Here is another solution that doesn't trigger the regular tap action after every long press.

Button("Button") {
    // No tap action here
}
.simultaneousGesture(LongPressGesture().onEnded { _ in
    print("Long-pressed")
})
.simultaneousGesture(TapGesture().onEnded {
    print("Tapped")
})

I learned about this in this blog post: Supporting Both Tap and Long Press on a Button in SwiftUI

Note: This might not work as expected with Catalyst, which you can learn more about in the blog post above.

Please check if this works for you:

Button("Button") {
    print("tapped")
}
.simultaneousGesture(LongPressGesture().onEnded { _ in
    print("long pressed")
})

Please note that tap action is executed after every long press in the above code. You can handle this with a simple Bool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM