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
sarah12345
1,509 PointsWhere is the code that binds a function to a button?
I get that we can drag the button into the controller and then write a function that will get executed when the button is pressed. I also see that I can right click the button and see the functions that will get triggered when a particular event happens. But shouldn't I be able to see some swift code for that somewhere? I searched for the name of my function, and it only comes up in the storyboard and in the controller. No real code to bind them together. It seems strange that there wouldn't be a way to see the raw code that makes that happen other than the popup properties inspector (whatever it's called).
2 Answers
sarah12345
1,509 PointsOK, based on my git diff, I can see it in the xml file for the storyboard. And I can basically tell from a "Find" search where it is. I'm still surprised that it's just xml. But what about finding usages easily? Doing a text search seems cumbersome. I googled and found that there is an icon in the top right corner that's supposed to show the callers of the function, but in this case none are shown even though it's hooked up to a button.
Gabe Nadel
Treehouse Guest TeacherIf I understand you correctly, you'll want to use the "addTarget(_:action:)" method. This is how you programmatically assign an IBAction to your button. There are versions for both Swift and Obj-C. See below for some docs and examples.
Obj-C Example:
[button addTarget:yourObject action:@selector(yourMethod:) forControlEvents:UIControlEventTouchUpInside];
Swift:
btn.addTarget(self, action: Selector("testp"), forControlEvents: UIControlEvents.TouchUpInside)