Your First iOS App: Using Interface Builder via XIBs (Xcode 7.2, Swift 2.1)

Part 2

Dan Stepanov
10 min readFeb 10, 2016

This is Part 2 of a 3 Part tutorial that follows Apple’s old “Your First iOS App” tutorial, but implements all of the user interface elements via XML Interface Builder (XIBs) using Swift. View Part 1 or check out the complete code on Github.

To learn more about my work, visit my website.

The next step is to familiarize ourselves with and setup our XIB.

1. Initial XIB Setup

Go back to your MainViewController.swift file. Similar to the app delegate, this comes with some helpful methods to handle different points in the life cycle of the UIViewController class. It should look a little like this:

One of the important aspects of a good developer is clean code. Thus, you want to remove any code that you don’t utilize. In this case, go ahead and delete lines 10 through 26 as they aren’t relevant to this project.

A key benefit to using XIBs is that it gives us a great separation of our business logic (calling APIs, manipulating data, assigning data, etc) and our views (definition of views, view properties, and their layout). In regards to our MainViewController, everything that deals with our views will go in “MainViewController.xib” and everything else will be in our “MainViewController.swift” file.

For now, we only care about defining our text field’s view; that is, its properties and its layout. So let’s navigate to our “MainViewController.xib” using the right side menu (Navigator). Once here, you should something like this:

  • Section 1 is our Navigator, you can use this to move between the other files in the project.
  • Section 2 is the Document Outline, it provides a simple hierarchal overview of what is in the current view.
  • Section 3 is our actual playground (the Interface Builder), our current view.
  • Section 4 contains our tools (Utilities) that we will use in conjunction with the current view to build our UI.

When working with a XIB, we will spend most of our time in sections 3 and 4.

First things first, at the bottom of the main view, find this

After clicking on it, change it to this

Once you’ve done that click the green circle to finalize the change. Your main view should change it’s size and should now look more like an iPhone.

This is not a necessary change but will provide us with a better understanding of what our view will look like when run on an actual device.

Your view should now look like this

Now we’re ready to work! We will now add elements to the user interface — a text field, a button, and a label.

2. The Text Field

In the Utilities, find the Object Library, it looks like the image to the adjacent image. Now, use the bottom “Filter” search bar and begin typing “text field.”

You will see the only result should be “Text Field.” Drag and drop this item into our main view, closer to the top of the page.

Once it’s on the page, you can make it larger by simply clicking and dragging the frame. Your view should look like the one below.

You will also notice that once you drag the text field into the view, it appears as a sub-branch in the Document Outline titled “Round Style Text Field.” We now want to adjust the properties and the layout of the text field.

First we’ll adjust a property of the text field. Make sure the text field is selected. The area above the Object Library in the Attributes Inspector is where you can modify the text field properties. Find the “Alignment” property and set the alignment to center by clicking this button.

As simple as that, now you have centered the text in the text field! Feel free to play around with the other properties like text color, placeholder text, etc.

Now, we’re gonna move onto adding layout constraints in Interface Builder so that our text field is properly placed on the screen. Once again, make sure the text field is selected and now look for these 3 buttons at the bottom of the main view.

From left to right, these buttons are as follows:

  • Align — Allows you to align various axes of the current view to axes of its parent view. (Think center align horizontal and center align vertical)
  • Pin — Allows you to create a new constraint between the current view and another view.
  • Resolve Auto Layout Issue — I cannot, in good faith, recommend that you ever hit this button. Once you hit this button and select an option, you potentially throw all logic and reason out the window. I would only recommend using this if you are familiar with AutoLayout in Interface Builder and how it resolves issues.

We want to introduce 3 constraints using AutoLayout

  1. Align Vertical Center of Text Field with Vertical Center of its Parent (View)
  2. Set the Top of the Text Field to be 10% of its Parent View’s height
  3. Set the Width of the Text Field to be 90% of its Parent View’s width

The numbered instruction sets below correspond to the numbered constraints above:

  1. Ensure the text field is selected and click the Align button. Next, check the box that says Horizontally Center in Container and click Add 1 Constraint. If any red lines show up, disregard them for now.
  • Red lines simply indicate that more constraints are required in order to properly layout the view.
  • Yellow lines indicate that the current view doesn’t match the current constraints
  • Blue lines indicate that the current view matches the constraints and that there are sufficient constraints to properly place the view

2. Ensure the text field is selected and right-click the text field, hold and drag to the parent view. Let go and you should see this window appear.

Go ahead and click Top Space to Container. However, this isn’t quite the constraint we want so we need to edit it. Click on the newly created vertical line that extends from the top of the text field to the top of the parent view. Now a window like this should appear on the right.

Your constant may be different than mine but that shouldn’t matter. Change the values on your page to match the ones below. This creates a constraint (layout relationship) ensuring that the top of the text field is 10% (See Multiplier) of the height of the screen (See Second Item).

Additionally, ensure that the value for Constant is set to zero.

Once again some colored lines may appear on the main view but disregard them for now. We will deal with them once we have introduced all of our constraints.

3. For our last constraint, again, ensure the text field is selected in the main view. Once again, right-click the text field and drag out to the parent view. This time when you let go and the screen below appears, click Equal Widths.

As before, this isn’t quite the constraint we wanted so we’re going to modify it a bit. You’ll notice that as you add constraints, they appear in the Document Outline under a parent group titled Constraints. Go ahead and click on our newly created constraint for the width (the only one with “width” in the name). When the constraint is expanded on the right hand side of your screen, change the value of Multiplier from 1 to 0.9.

Now, click back on to the text field and you should see quite a bit of yellow lines. You should also notice that a yellow arrow has appeared in the Document Outline.

Click on this yellow arrow and you will be taken to a screen that presents an overview of the layout conflicts. It will tell you what properties are expected to be versus what they currently are in the main view. There is also a yellow triangle on the right of this view. See below.

Mine looks like the following. To resolve the constraint issues, click on the yellow triangle. This will present you with several options. See below.

The issue is that, using the constraints we created, we have defined where we want the text field to be but the text field in the main view doesn’t match those constraints.

Instead of forcing a decision, Xcode allows you to decide whether to update the main view to match your constraints or to have Xcode adjust your constraints to match what the main view currently looks like. In this case, we know our constraints are right so we will select Update frames and click Fix Misplacements. If you click back into the main view, you’ll notice a lot of blue lines now! You will learn to love blue lines.

If you run the app, you should now see the text field at the top of the screen. Clicking inside will bring up the keyboard and allow you to type. While the keyboard appears automatically, we have to add to code make it disappear ourselves.

The key is implementing a “delegate method” of the UITextField. Delegate methods are like helper functions for the objects in your application, and can sometimes help pass data between two classes. In order to implement the UITextFieldDelegate, we add it to the line containing our class definition in MainViewController.swift

class MainViewController: UIViewController, UITextFieldDelegate {

And then we set MainViewController.swift as the delegate within our viewDidLoad method.

Right below super.viewDidLoad() line, add

textField.delegate = self

This lets the application know where to look for the implementation of the delegate methods, which in this case is inside Self — a reference to our MainViewController class.

Now that we implemented the text field delegate, the delegate method we need to dismiss the keyboard is called “textFieldShouldReturn.” This function is called every time the user presses the “return” button on the keyboard.

Information about a class’s delegate methods is in Apple’s documentation. You can find the “textFieldShouldReturn” method in the UITextFieldDelegate reference article.

Since this is more business logic than view work, we will add it below the viewDidLoad method in MainViewController.swift:

func textFieldShouldReturn(textField: UITextField!) -> Bool {}

Dismiss the text field programmatically by adding the following lines:

func textFieldShouldReturn(textField: UITextField) -> Bool {// Dismisses the Keyboard by making the text field resign
// first responder
textField.resignFirstResponder()

// returns false. Instead of adding a line break, the text
// field resigns
return false
}

However, we haven’t yet created a reference to our text field from the XIB. Xcode knows to add the text field upon building the app but in order to access and manipulate the text field from our .swift file, we need to create an IBOutlet linking the text field to our code. To do this, we will need to open the Assistant Editor. If you aren’t familiar with the Assistant Editor, it’s the middle button in this set of buttons at the top bar of Xcode.

The button with two circles is the Assistant Editor

If you haven’t already, navigate to the MainViewController.xib file and click the Assistant Editor button. Your view should now be split in two like this:

To make room, go ahead and hide the Utilities by clicking the right-most button in this set at the top of the screen:

And hide the Document Outline by clicking this button at the bottom of the XIB view.

Now, Xcode will look like this:

Go ahead and right-click the text field in the XIB file and drag your cursor all the way over to the .swift file just above the viewDidLoad method. You should see this little window pop up:

Since this will be an Outlet, just go ahead and name this “textField” and click Connect. Now, you should see the error icon go away and, if you run the app, clicking on the text field pulls up the keyboard and the Return button dismisses the keyboard. Additionally, we can now directly manipulate our text field from the .swift file.

In the next part of this tutorial, we will add the Label and the Button.

Part 3 Coming Soon!

--

--