Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Bryan Krossley
1,644 PointsProgrammatically Call Action
Hi, Is it possible to call an IBAction programmatically?
Thanks, Bryan
2 Answers
Michael Hulet
47,913 PointsSure. Just call the method that the IBAction invokes on its own. For example, in one of my apps, I have this IBAction and the following UIButton defined:
@property (strong, nonatomic) IBOutlet UIButton *facebookButton;
-(IBAction)postToFacebook:(UIButton *)sender;
I could later call this in my code like this:
[self postToFacebook:self.facebookButton];
If you define the IBAction as taking no arguments, then you don't even need to define the IBOutlet to its trigger (in this case, a UIButton)
Bryan Krossley
1,644 PointsThanks for the tip. Here is what worked
orangeBtnPressed(orangeBtnPicked)
Michael Hulet
47,913 PointsAwesome. Glad I could help
Bryan Krossley
1,644 PointsBryan Krossley
1,644 PointsI should have mentioned that I am using swift. Here is my action and outlet
Michael Hulet
47,913 PointsMichael Hulet
47,913 PointsOkay, I just started the Swift course this morning, so I'm far from fluent in it (you'll probably have to edit this a little), but the concepts are mostly the same. You just call the
IBAction's function and pass in the corresponding trigger as thesender. In this case, I think it would be something like this:orangeBtnPressed(sender: orangeBtnPicked)Essentially, what I'm trying to say is that an
IBActionis just like any other function (in fact,IBActions andIBOutlets don't actually exist. They're just there so Interface Builder knows what you're talking about when you're moving stuff around on your.storyboardfile, but the compiler totally ignores those keywords, just like it would a comment). Because it's just like any other function, you can call it anytime you want like any other function. In this case, it requires asenderas a parameter, so it's just easiest to pass in the trigger object that would normally be passed in