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

iOS

Programmatically Call Action

Hi, Is it possible to call an IBAction programmatically?

Thanks, Bryan

2 Answers

Sure. 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)

I should have mentioned that I am using swift. Here is my action and outlet

    @IBAction func orangeBtnPressed(sender: UIButton) {
        buttonNumberIndex = [0]
        playerNumberCatcher()

    }

@IBOutlet weak var orangeBtnPicked: UIButton!

Okay, 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 the sender. In this case, I think it would be something like this:

orangeBtnPressed(sender: orangeBtnPicked)

Essentially, what I'm trying to say is that an IBAction is just like any other function (in fact, IBActions and IBOutlets 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 .storyboard file, 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 a sender as a parameter, so it's just easiest to pass in the trigger object that would normally be passed in

Thanks for the tip. Here is what worked

 orangeBtnPressed(orangeBtnPicked)

Awesome. Glad I could help