swiftibactiontarget-action

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?


Solution

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