In Xcode, to connect objects within your view to actual code you can use IBActions. This article will show you how to create IBActions in Swift 3 using Xcode 8.
With IBActions
, you can connect actions from your Storyboard back to code within your ViewController.swift class. In this example, you will be shown how to execute some code when a button is pressed within your application.
Creating IBActions is most easily done by clicking and dragging within Xcode. To start with, it is recommended that you use the Assistant Editor
. This can be accessed by clicking on the icon in the top right hand corner that contains the overlapping two blue circles. You can then have your Storyboard and ViewController.swift file open together in a vertical split view.
Now in order to reference your objects within the ViewController.swift class, simply press ctrl
on your keyboard and click on the object on your View.
When you move your cursor across the screen a blue line should appear from the object. You will use this blue line and drag it into the ViewController.swift class.
As you can see from the image, you will be asked to choose the connection type, either Outlet, Action or Outlet Collection. A menu will popup as soon as you let go of the ctrl
key.
Choose Action
from the connection dropdown and give your action a name. There are many events that Xcode provides that we can use for the IBAction. Select Touch Up Inside
which simply means that the IBAction will be executed when the button is pressed in the application.
After pressing the Connect
button, Xcode will have generated an IBAction for you.
If you’ve read the IBOutlets in Swift article, you’ll know that you can reference an object using an IBOutlet using a property.
In the above image, we have a myButton
property, and therefore we can use this property to manipulate the button’s behaviour in the view.
For example, to change the button’s title, in Swift 3 we can use setTitle
.
When running the application, you will see that the button title changes from “Press Me!” to “I’m a new title”.
That concludes a basic code example of how to manipulate the behaviour of objects within your Storyboard. There are of course more complex scenarios where you might need additional code to execute, but hopefully this will provide you with a basic understanding of how IBActions work within Xcode.