Reputation: 8635
I would like so that when someone clicks on a button, it triggers function X, but afterwards, it triggers func Y. This should be back an forth.. First time they click on button A, trigger function X, second time, trigger function Y, third time trigger X. How do we trigger actions in code instead of the storyboard using swift?
Upvotes: 0
Views: 47
Reputation: 318774
Hookup your button to a single action like you normally would:
@IBAction func buttonHandler(_ sender: UIButton) {
}
Then add two functions that you wish to alternate between:
func handlerX() {
// Do the first set of operations
}
func handlerY() {
// Do the second set of operations
}
Then add a property to your view controller that keeps track of which one to call:
var handlerState = true
Now you can update the action as follows:
@IBAction func buttonHandler(_ sender: UIButton) {
if handlerState {
handlerX()
} else {
handlerY()
}
handlerState = !handlerState
}
Upvotes: 2