Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any differences between @objc and IBAction when programmatically creating UIButton event?

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?

like image 779
J. Doe Avatar asked Mar 10 '18 14:03

J. Doe


People also ask

What is IBOutlet and IBAction in Swift?

@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.

How does IBAction connect to storyboard?

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.


1 Answers

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.

like image 71
Tamás Sengel Avatar answered Oct 21 '22 11:10

Tamás Sengel