IBOutlet and IBAction in Swift

linux-user picture linux-user · Sep 14, 2015 · Viewed 35.4k times · Source

I connected a IBOutlet and IBAction to my button variable from Interface Builder to my View Controller. How do I add an action method to the button in Swift? This code doesn't seem to work.

@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){}

The Objective-C equivalent I found is:

@interface Controller
{
    IBOutlet id textField; // links to TextField UI object
}

- (IBAction)doAction:(id)sender; // e.g. called when button pushed

Answer

Caleb Kleveter picture Caleb Kleveter · Sep 14, 2015

When you attach a button to the viewController and create an action (IBAction) using ctrl-drag, you create a method that looks likes this in Swift (if it doesn't have arguments):

@IBAction func buttonAction() {}

In Objective-C the same thing will look like this:

- (IBAction)buttonAction {}

So that means that @IBAction func OK(sender: UIButton){} is an action method.

If you want to know about the sender argument, I would recommend this SO post.

Edit:

For what you want to do, I create an IBOutlet and an IBAction, that way I can change its attributes with the outlet variable, and have the action side of things with the IBAction, like what you show above:

@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){} 

For example, if I want to hide the button, I would put this code in the viewDidLoad

OK.hidden = true

The OK in that code is for the outlet variable, if I wanted to print "You pressed me" to the console when the button is pressed, I would use this code:

@IBAction func OK(sender: UIButton){
  println("You pressed me")
}

Above I am using the action to print "You pressed me" to the console.

A few things to note:

When Swift 2.0 gets released println will get changed to print. Also with you action and outlet, I would suggest giving them differing names, to make it easier to differentiate the two, something like this:

@IBOutlet var okOutlet: UIButton!
@IBAction func okAction(sender: UIButton){} 

Along with that, you should use camel case when naming variables, constants, functions, etc.