Search code examples
xcodeswiftuiios13

Any SwiftUI Button equivalent to UIKit's "touch down", i.e. activate button when your finger touches?


For SwiftUI the default button behavior is equivalent to UIKit's "touch up inside", which activates when your finger touches the button then raises while within the bounds of the button.

Is there any way to change this to "touch down" so the action closure is run immediately when your finger touches the button?


Solution

  • You can use a DragGesture with a minimumDistance of zero and define a closure for DOWN (onChanged()) or UP (onEnded()):

    struct ContentView: View {
        @State private var idx = 0
    
        var body: some View {
            let g = DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({
                print("DOWN: \($0)")
            }).onEnded({
                print("UP: \($0)")
            })
    
            return Rectangle().frame(width: 100, height: 50).gesture(g)
        }
    }