Your First iOS App (IV): Building the User Interface - Digital Leaves
page-template-default,page,page-id-1822,qode-social-login-1.0,qode-restaurant-1.0,ajax_fade,page_not_loaded,,select-theme-ver-4.1,wpb-js-composer js-comp-ver-5.2,vc_responsive

Welcome back! This is the fourth episode of the series “Your First iOS App”, in which you will learn how to create your first native iOS App in Swift. In the previous episode, we explored the MVC paradigm, and how it applies to our Xcode projects. Today, we are going to address the visual aspect of the app’s creation, i.e: the user interface. We will learn about the Interface Builder, its elements, and how to manage them. Let’s start!

Understanding the dicothomy between visual representation and code

All standard visual elements and controls in iOS belong to a framework called UI (User Interface). This “UI” tag is prefixed to every element that belongs to that framework. Thus, a view is an UIView, a label is a UILabel, and a button is a UIButton. Most controls and visual elements in the UI framework inherit from UIView, so they are all views, basically rectangles with a frame and a background color. The Interface Builder (or IB for short) is a tool included in Xcode to visually edit the view hierarchy of the View Controllers of your application.

Even though we said that a view is the visual element that display the information as defined by the view controller, the view is nothing more than a swift class. Plain swift code. The visual representation that you see in the Interface Builder is nothing more than a XML way of defining the visual aspect of the view. A storyboard (UIStoryboard) is nothing more than a XML file with a collection of UIViewControllers defined and, for each of them, the description of the views contained inside, defined as a set of elements with a type (button, label, etc), position, size, and other properties such as colors, texts, etc. As an example, an storyboard’s XML could contain this definition:

  • There is a view controller, it’s the initial view controller.
    • The view controller contains a main view, white, covering all the view controller.
      • The view contains a label, called label1, starting at point (x1, y1) with size (w1, h1) and a text of “Hello world”
      • The view contains another view, called view1, starting at point (x2, y2), with size (w2, h2) and a blue background color.
      • The view contains a button, called button1, starting at point (x3, y3), with size (w3, h3), with text “Click me” and an action that, when clicked, should execute a method called “userHasClickedOnTheButton”.
  • There is another view controller, called viewController2
    • The view controller contains a main view, white, covering all the view controller…

In the early days of Xcode (when Swift didn’t exist yet, the programming language for iOS was Objective-C), there was no Interface Builder as we know it now. In those days, we used to define the view hierarchies for view controllers programmatically, meaning instantiating the views and controls in code, setting their properties (position, size, etc) and adding them to the view hierarchy one by one in code. Later, Apple released the Interface Builder as a separate application, so you could visually compose your view controllers’ views, but linking them together was kind of a complicated process. Luckily for us, Apple finally integrated the Interface Builder with Xcode, allowing for a much better and easy way to compose the visual interfaces for your application and link them to the behavior via code.

Hands-on with the Interface Builder

Enough talk already! It’s time to start adding stuff to our visual interface. In the project navigator, click on the Main.storyboard file. As we saw earlier, a storyboard is just a visual representation of a set of view controllers that define the user interface of our App. Usually, a storyboard will contain several view controllers, each of them filled with views and controls. However, our sample application will have just one view controller, and in this unique VC, we are going to add the visual elements we need for our “Hello World” application. First, you need to go to the first (an only) view controller, that currently is completely blank, as appearing in the figure.

Make sure you have the Utilities inspector (the left-most button in the top bar) selected and showing at the right side. Click on the view controller at the left until it’s selected, and then, in the utilities panel at the right, click on the icon that has a square inside a circle until you see something similar to the figure at the left. That is the “Object library”, and contains all the basic visual elements from UIKit that we can add to our storyboard. We can add new view controllers to our storyboard here, or add elements and controls to the views of the view controllers that we have already there.

Take a moment to explore the objects in the library. Notice how the first elements appearing, in bright yellow colors, are types of view controllers. Normally, you will probably use the first one (View Controller), to add new view controllers to the scene. Then, we have the controls to be added to the view of a view controller: labels, buttons, text fields, sliders, etcetera. Every control serves a concrete function, from displaying the user position in a map to allow interactions via a user click. When you add one of these elements to the view controller’s window, you are actually inserting it into the view of the view controllers. Those views are called “subviews” of the main view, and these subviews can have also subviews of their own, forming a hierarchy.

For our sample application, we will need just three main elements: a label, a textfield and a button. The label is where our initial “Hello World!” text will be placed, and we will update this text when the users enter their names in the textfield. Then, we will add the textfield that will allow the user to enter a name. Finally, we’ll set a button to change the label in response to the new text typed by the user.

First things first. In order to add the label to the view of the view controller, we will look in the object library for the “Label” element, and then drag and drop that element to the view controller’s view. If everything goes well, you should see a label appearing, with the text “Label”. Next, you are going to drag and drop the label to the top left side of the parent’s view. I want you to place it in the top-left margin. As you approach this point, you will notice that some blue guides will appear to help you place the label. Follow them and drop the label when you see both, as in the figure in the left.

These guides help you set the elements to “pin” them later using AutoLayout. AutoLayout is a mechanism to define the placement and size of the views and controls in a view controller, and allows us to build auto-adaptive and responsive interfaces for different types of devices, such as iPhones, iPads, etcetera. We will talk about Autolayout in another series of tutorials, but for now, just leave the view there, at the top-left edge.


With our label in place, we are going to add the remaining elements. First, we will add the textfield for the name of the user. Look for an element called “Text Field” and drag&drop it like you did with the label. We want it to be in the center so, after dropping it, move it to the center until you see two blue guides indicating that the element is centered. Next, add a Button. Repeat the exact same procedure and move it just below the textfield, centered. You will notice that the guides also relate different controls, like the textfield and the button in this case. This will be very useful for us to define AutoLayout rules later.

Ok, so now that all of our elements have been added to the view of the view controller, run the application. You should see that now our blank screen is not blank anymore, but it contains all of our elements in place.

You might notice that, if you run the application in a simulator whose size is different from the size that you are using in the Interface Builder, your interface will appear displaced. The elements would not be in the spots you left them. That’s because we have not pinned them or defined their sizes and alignments with AutoLayout, we just dropped them in the view. In the “AutoLayout Survival Guide” series, we are going to learn how to fix this situation and build responsive interfaces for most iOS devices.

Congratulations! You just added your first control to the view of a view controller. Now, it’s time for us to set some of their attributes to make this interface look better.


Modifying the Attributes of a Control

Now, there are some things that we could do to improve the look of our controls. Notice how all of them have placeholder texts (the label says “Label”, and the button says “Button”). We want also to set a basic value for the textfield, like “World”, so if the user clicks the button without entering any name, the label would still say “Hello, World!”.

To modify the attributes of a control, we need to open the “Utilities area” in the right, by clicking on the upper-right most button, and then clicking on the attributes inspector button. Now, if you click on the label in the view controller, you will see something similar to the image in the left.

Here you will find all the attributes you can modify for the label, including the text, color, font and background of the label, among others. You will see that the text textfield contains “Label”. You can click on it and edit it to “Hello, World!”, click enter and, voila! you will see the label change in the Interface Builder to reflect this change. You just changed one of the attributes of the label.

Make sure to change the text for the textfield to “World”, and the text of the button to “Say Hello”. Then, take some time to explore and experiment with the other attributes of your controls, including color, font sizes and alignments. It’s really easy to change the appearance of a button or a label using the attributes inspector. If you kind of mess up the control and don’t know how to go back to its standard configuration, don’t panic. Just delete the control by selecting the control and pressing backspace. Be careful not to select the view controller and press backspace, because then you will remove the complete scene. If you do so, however, simply pressing Cmd+Z will undo your change and get your view controller back.

When you have finished with all your modifications, you should end up with a situation similar to the one depicted in the figure at the right, with a label on top reading “Hello World!”, a textfield centered both horizontally and vertically, and a button horizontally centered below the textfield. If you run into trouble, or are unable to set the elements properly, don’t hesitate to contact me and ask.

If you run the application now, you will hopefully see all the elements with the proper values, so we are ready to go! or not? Try clicking on the “Say Hello” button… nothing will happen. That makes sense, as we have not yet stablished a communication between our visual controls and the code file ViewController.swift that will allow them to interact.

In order to do that, we first need to set a link between the visual representation of our controls and the code file via outlets and actions, and then, define the interactions in code in the ViewController.swift file. In this episode of the tutorial, we will be taking care of the first part, and in the next episode, we’ll learn to add the functionality programmatically. How? keep on reading… :)

Outlets and Actions

So how do we communicate between code and visual representation? How do we reference a label from code to change its text or font size, or how do we get notified in code when a button is clicked? Thanks to outlets and actions.

Let’s revisit the graph we saw in the previous article to explain the code part of the view controller and the visual representation of the view in the interface builder:


You might notice that we have defined three variables in our view controller’s class:

These variables are: a label (UILabel), called helloWorldLabel, that’s used to show one or several lines of read-only text, a textfield (UITextField) called inputTextField, that’s used to get data (text) from the user, and a button (UIButton) called sayHelloButton, that’s used to launch an action when the user clicks on it. You will notice that these variables have been defined with this @IBOutlet keyword, so what is this? This is a tag so Xcode knows that these variables are “outlets” to controls or views in the interface builder. An outlet works as a “link” from the code to the visual representation in IB. Thus, once the outlet is set, I can modify the text of the label anytime in code by just typing:

Easy as pie, right? Being able to modify the visual elements of our interface is essential for building rich, expressive and interactive applications.

So how do you set an outlet? It’s really easy. You just have to follow these steps:

  1. Make sure you have your Main.storyboard selected. Also, make sure that the Assistant Editor is showing, so you have the view controller with the control you want to outlet at the left, and the code at the right.
  2. Make sure you are editing the class that corresponds to the view controller we have at the left. In order to do that, click on the file selection depicted in number (2) and choose “Automatic”. If you click on the view controller on the left, you should see your ViewController.swift class at the right. This is to make sure we are going to place the outlet in the view controller’s class.
  3. Now, while holding down the Ctrl key, click on the element you want to create the outlet for (say, the “Hello World!” label) and without releasing the key, drag all the way to the right just below the “class ViewController: UIViewController” line. You should see a blue line appearing from the label and following your mouse pointer.
  4. When inside the class, under the class definition line, release the mouse click (while still holding Ctrl) and, if everything went well, a dialog will appear to allow you to name your outlet.

Notice how the Connection specifies “outlet“, indicating that we are going to create an outlet reference for the visual element. You’ll see some other options like type, storage, etc, but for now, just choose a name and click Connect. You will see a new line of text appearing with the variable definition, like the ones I depicted earlier. Now, you just have to repeat this process for the rest of the elements (the textfield and the button). You will notice how the type of the variables change accordingly.

Don’t worry if you can’t get it the first time. Probably you released the mouse or the control key too soon. Just try again. It might take you some time getting used to it, but once you do, it’s an easy process. ^ractice makes perfect.

Congratulations! You just created an outlet from a variable to its visual representation in Interface Builder. From now on, you will be able to modify any visual element at runtime with code instructions.

Now, we are able to set the label to any name we want. If the user enters “John” in the textfield, we will be able to get the text of the textfield via its text property (self.inputTextField.text), and then compose a “Hello, John!” string and set our label to this text to

greet the user with a personalized message. That’s cool! But wait… how do we get notified that the user clicked our “Say Hello” button? That’s what actions are for.

An action is also a link from code to visual interface, but in the opposite direction. Actions are used to react to user’s interaction with our visual components. In our case, we want to define an action that will be triggered when the user clicks on the “Say Hello” button. In order to do that, you will follow the exact same procedure that you followed for creating the outlet for the button, but this time, when the dialog for the outlet appears, in the “Connection” selector, you will choose “Action” instead of “Outlet”. The dialog will adjust with some other properties, but you just need to give it a name like you did with the outlet. This time, however, this name will indicate an action, so call it something appropriate like “sayHello” or “sayHelloButtonClicked”.

The following text should appear in your class:

This action is nothing more than a method (or function if you like). The code that you include inside will be executed when the user clicks on the button. There are many type of events that might be triggered for every control. When you define the action visually, Xcode will set the most common one for you. In the case of the button, this event is called “Touch Up Inside”, i.e: the common interaction of clicking on a button.

Congratulations! You just created an action from a button to be able to execute code when certain events happen in the visual interface. From now on, you will be able to interact with your visual interfaces in code and build rich, interactive user interfaces.

Where to go from here.

In this episode of “Your first iOS App“, we learned about the Interface Builder, storyboards, and the visual representation of view controllers and subclasses of views. We also learned how to build interactions between the visual representation of controls such as labels and buttons, and our code, in order to be able to update our user interface and react to events triggered by the user.

In the next episode of the series, we will add the required functionality to make the application work, so when the user enters a name in the textfield and clicks on “Say Hello”, the label will update.

Before you continue...

Hi there! I created the Digital Tips List, the newsletter for Swift and iOS developers, to share my knowledge with you.

It features exclusive weekly tutorials on Swift and iOS development, Swift code snippets and the Digital Tip of the week.

Besides, If you join the list you'll receive the eBook: "Your First iOS App", that will teach you how to build your first iOS App in less than an hour with no prior Swift or iOS knowledge.

I hate spam, and I promise I'll keep your email address safe.