Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI button action as soon as button is clicked not on click release

I want to call the action as soon as the button is clicked/tapped in SwiftUI Button. How can I implement this?

like image 823
Roshan Chamlagain Avatar asked Sep 19 '25 18:09

Roshan Chamlagain


1 Answers

Here is a possible approach - to use custom ButtonStyle to inject custom touch down action

Tested with Xcode 12 / iOS 14

struct PressedButtonStyle: ButtonStyle {
    let touchDown: () -> ()
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(configuration.isPressed ? Color.gray : Color.blue)
            .background(configuration.isPressed ? self.handlePressed() : Color.clear)
    }

    private func handlePressed() -> Color {
        touchDown()           // << here !!
        return Color.clear
    }
}

struct DemoPressedButton: View {
    var body: some View {
        Button("Demo") {
            print(">> tap up")    // << can be empty if nothing needed
        }
        .buttonStyle(PressedButtonStyle {
            print(">> tap down")
        })
    }
}
like image 148
Asperi Avatar answered Sep 21 '25 08:09

Asperi