Connect Storyboard Objects to Code

If you’re using the Storyboard, you need to know this

Image for post
Image for post
Photo by Joshua Ness on Unsplash

The idea of this tutorial is to add objects to the storyboard and be able to update them programmatically in the `UIViewController`. Possible? Sure. How? This article!

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 11.4.1, and Swift 5.2.2.

Updated for Xcode 12.2 and Swift 5.3.1

The completed code is available HERE

Prerequisites:

The step-by-step, adding a UILabel to the Storyboard

This is covered in my Single View Application article, but pretty much all this means is that you need to open up Xcode and New>Single View Project. I named mine StoryboardOutlets.

Select the `Main.storyboard` file from the project inspector on the left-hand side. The `UIViewController` appears, and allows us to use the + symbol to be able to add objects

Image for post
Image for post

which can then be added by choosing UILabel

Image for post
Image for post

and a simple drag-drop operation will help us out here.

Image for post
Image for post

Now by dragging and dropping the UILabel and matching the blue lines when we drop it onto the centre of the UIViewController it will match to the centre — exactly what we would want!

The UILabel needs to be connected to the ViewController.swift file (assuming that you have left the UIViewController called *ViewController*). We are going to name this UILabel instance as *label* (creativity is everything, right?).

Loading the Assistant editor

With the Storyboard still selected, we can select the following jump bar icon:

Image for post
Image for post

which when placed on the jump bar is towards the right of the screen

Image for post
Image for post

As shown, select *Assistant*.

The following part is actually quite easy / tricky depending on how you see it. We need to control-drag from the UILabel to the ViewController.swift file.

Image for post
Image for post

as you see, I’ve then named the outlet as **label**

The UILabel can then be accessed from the view controller as normal. That is, we just set label.text = “Hello, World!” as I’ve done in the viewDidLoad() function.

Image for post
Image for post

which leaves us with the following view controller code.<br/>

Image for post
Image for post

Conclusion

This is a task, that if you use the storyboard you’ll encounter often while producing great apps in Swift for iOS. I hope this short article really helps you out and brings clarity to this process. Oh, and if you want to see the completed Repo with this work I’ve a link around here somewhere. StoryboardOutlets

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store