While using storyboard we can programatically click a button or a field by using
@IBOutlet weak var negativeButton: UIButton!
negativeButton.sendActions(for: .touchUpInside)
How do I recreate the same using SwiftUI?
It is impossible to do the same in SwiftUI, SwiftUI does not know even Button exist "As Object! But as Render and it's duty exist", the why of using a Button is it's functionality in SwiftUI, that means firing up an Action or ()-> Void, so you do not need also you cannot programatically tap the Button, because you can run anytime and anywhere it's action.
For example: you can run actionOfButton()
from the place you want programmatically tap the Button, it would work the same. if your Button changes it's appearance depending on each tap, you should make does happen in the actionOfButton()
, So with that said, you could have action and render at the same time, and that's Wrap-Up for tapping a Button programatically in SwiftUI.
import SwiftUI
struct ContentView: View {
var body: some View {
Button("tap") {
actionOfButton()
}
}
func actionOfButton() {
print("Hello, world!")
}
}