How to achieve UIKit's "touch down" in SwiftUI?

This isn't an obvious thing to do, but if you play around with the way Button is designed you find out that it uses either PrimitiveButtonStyle or ButtonStyle protocols.

I would probably go with PrimitiveButtonStyle and implement a custom style for your button.

In the end you will have something like this:

Button(...)
  .buttonStyle(MyButtonStyle(/* here you can have expose anything you want */))

This approach allows you to create buttons with custom styles that implement custom gestures.

Here is a quick prototype, but it looses the default button Style.

struct MyButtonStyle: PrimitiveButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration
      .label
      .onLongPressGesture(
        minimumDuration: 0,
        perform: configuration.trigger
      )
  }
}

struct ContentView: View {
  var body: some View {
    VStack {
      Button("A") {
        print("A pressed")
      }
      Button
        .init("B") {
          print("B pressed")
        }
        .buttonStyle(MyButtonStyle())
    }
  }
}
6 Likes