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!
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With