Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an IBAction for a button programmatically-created based on user input

I am creating a small project involving the creation of a UIButton based user input.

I know how to programmatically add the button but I am not sure how I can make the button perform actions I want it to perform. I know for a UIButton created directly on the storyboard, an IBAction can be linked into the file to do so. Can anyone show me how this can be done with a programmatically created button?

Thank you so much!

like image 578
Erica wang Avatar asked Dec 08 '16 21:12

Erica wang


2 Answers

use addTarget to bind an action to a method

func buttonClicked(sender: UIButton){
    print("button Clicked")
}

then add target to button

var button = UIButton()
button.addTarget(self, action: #selector(self.buttonClicked(sender:)), for: .touchUpInside)
like image 189
Mohammadalijf Avatar answered Nov 14 '22 23:11

Mohammadalijf


Use the UIControl function addTarget(_:action:for:). You specify a target, an action (using the swift #selector(actionName(_:) syntax), and the event(s) for which you want the button to trigger the action.

When you're looking in the docs on an object like UIButton, remember to check it's ancestor classes as well. The addTarget(_:action:for:) function is defined in UIControl.

like image 27
Duncan C Avatar answered Nov 14 '22 22:11

Duncan C