Erica wang
Erica wang

Reputation: 111

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!

Upvotes: 8

Views: 4599

Answers (2)

Mohammadalijf
Mohammadalijf

Reputation: 1377

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)

Upvotes: 13

Duncan C
Duncan C

Reputation: 131398

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.

Upvotes: 1

Related Questions