Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add an action to a button programmatically in xcode

I know how to add an IBAction to a button by dragging from the interface builder, but I want to add the action programmatically to save time and to avoid switching back and forth constantly. The solution is probably really simple, but I just can't seem to find any answers when I search it. Thank you!

like image 621
aggiesfan64 Avatar asked Apr 30 '11 17:04

aggiesfan64


1 Answers

Try this:

Swift 4

myButton.addTarget(self,                    action: #selector(myAction),                    for: .touchUpInside) 

Objective-C

[myButton addTarget:self               action:@selector(myAction)     forControlEvents:UIControlEventTouchUpInside]; 

You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.

--

You'll need to pay attention to whether add colon or not after myAction in action:@selector(myAction)

Here's the reference.

like image 56
Nick Weaver Avatar answered Sep 21 '22 17:09

Nick Weaver