One of the features you can use to manipulate objects within the view are IBOutlets. This article will show you how to create IBOutlets in Swift 3 using Xcode 8.
IBOutlets are properties created within the ViewController class, the class that manages the view, which simply references an object created from the storyboard.
Creating IBOutlets is most easily done by clicking and dragging within Xcode, therefore it is useful to switch to 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 IBOutlets are properties, you will want to make sure that release your dragged blue just below the class declaration, but above and not inside any of the existing methods. The ideal place should be like the screenshot provided above.
When you release
ctrl, you will be prompted to choose either an
Outlet Collection. This example will be using
Outlet Collection can be used for hooking up multiple objects to an IBOutlet.
Choose a name from your outlet and leave the storage as
After doing so, you’ll see the
@IBOutlet weak var myLabel: UILabel! line of code added in your class.
If you’re familiar with declaring variables, you’ll notice that the label object in this example has been assigned to the
myLabel variable. We can then use
myLabel when referencing the label object within the ViewController.swift class.
To modify an object’s behaviour using code, you can use
IBActions where functions are created within the ViewController.swift file. This will be covered in the next post.