Reputation: 147
How can I make a UIButton
complete two separate methods when pressed?
Upvotes: 0
Views: 76
Reputation: 62052
If you're designing your view controller in an Interface Builder (either storyboard or xib), we can hook our button up to as many actions as we want.
Using the ctrl+drag method, we create a method to handle the button press:
And we can hook up as many methods to as many different actions as we want:
Here, this button is connected to three different methods.
We can do the same thing in code programmatically.
In Swift:
myButton.addTarget(self, action: "methodOne:", forControlEvents:.TouchUpInside)
myButton.addTarget(self, action: "methodTwo:", forControlEvents:.TouchUpInside)
myButton.addTarget(self, action: "methodThree:", forControlEvents:.TouchUpInside)
Or in Objective-C:
[myButton addTarget:self
action:@selector(methodOne:)
forControlEvents:UIControlEventTouchUpInside];
[myButton addTarget:self
action:@selector(methodTwo:)
forControlEvents:UIControlEventTouchUpInside];
[myButton addTarget:self
action:@selector(methodThree:)
forControlEvents:UIControlEventTouchUpInside];
We can hook up any number of events.
As a final note, I'm not sure there's any way to actually control the order in which the methods hooked up directly to the button are called. In this case, I hooked up the button to the methods in order: one
, two
, three
, but they appeared to be called in a different order: one
, three
, two
. They are consistently called in this order.
If it the order is actually important, then we should be hooking up our button just to a single method which then calls all the other methods in the explicit order we need:
@IBAction func buttonPress(sender: AnyObject) {
self.methodOne(sender)
self.methodTwo(sender)
self.methodThree(sender)
}
And to be honest, I'd say this should be the recommended approach anyway. It probably makes the source code a little easier to read.
Upvotes: 6