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?
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?
3
Answers
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 theactionOfButton()
, 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.The possible solution is to declare your action variables inside your structure view and whenever you need you can manually call the button action.
Here is the demo.
You can’t treat the SwiftUI button like the UIKit button. Because In SwiftUI View (Button) doesn’t have an object/outlet as you did in the storyboard so it doesn’t have a function like that.
Instead, you can create the function and you can use that function to trigger the button action and you can call that function from anywhere wherever you required.
Please refer to the below example for more clear understanding.