How to Programmatically Simulate a Button Tap in SwiftUI?

In UIKit, certain events like a button tap can be simulated using:

button.sendActions(for: .touchUpInside)

This allows us to trigger the button’s action programmatically.

However, in SwiftUI, there is no direct equivalent of sendActions(for:) for views like Button. What is the recommended approach to programmatically simulate a SwiftUI button tap and trigger its action?

Is there an alternative mechanism to achieve this(and for other events under UIControl.event) , especially in scenarios where we want to test interactions or trigger actions without direct user input?

In SwiftUI, there is no direct equivalent of sendActions(for:) from UIKit.

SwiftUI views are data driven. For example you could have a button that triggers an action:

struct ContentView: View {
    @State private var isTapped = false
    
    var body: some View {
        VStack {
            Button("Test Button") {
                isTapped = true
            }
            
            Text(isTapped ? "Button was tapped!" : "Waiting to be tapped")
        }
    }
}

In this case you could modify the state variable isTapped directly .

How to Programmatically Simulate a Button Tap in SwiftUI?
 
 
Q