When creating an eventhandler from a UIButton
from the Storyboard, Swift adds @IBAction
before func
. When adding an event programmatically to a UIButton
to a func
, Swift gives a error and says I need to add @objc
in front of my method, but when I add @IBAction
, it compiles as well.
Are there an difference between the 2 and which should I use when adding an event to my UIButton
programmatically?
@IBAction is similar to @IBOutlet , but goes the other way: @IBOutlet is a way of connecting code to storyboard layouts, and @IBAction is a way of making storyboard layouts trigger code. This method takes one parameter, called sender . It's of type UIButton because we know that's what will be calling the method.
You can check what outlets your buttons are connected to by right clicking on them. To connect a button to an action, hold down control while clicking and dragging from the button to the action you want to attach it to.
The IBAction
prefix already exposes the method to the Objective-C runtime, so there is no need to prefix it additionally with @objc
.
Since IB stands for Interface Builder, it's unnecessary to use it when you create a button programmatically. All it does (besides exposing the method to Objective-C) is make Interface Builder list the function as an action in the Connections inspector.
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