Home iOS & Swift Books iOS Apprentice

11
Navigation Controllers Written by Eli Ganim

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

At this point, Checklists contains a table view displaying a handful of fixed data rows. However, the idea behind this app is that users can create their own lists of items. Therefore, you need to give the user the ability to add to-do items.

In this chapter you’ll expand the app to have a navigation bar at the top. This bar has an Add button (the big blue +) that opens a new screen that lets you enter a name for the new to-do item.

When you tap Done, the new item will be added to the list.

The + button in the navigation bar opens the Add Item screen
The + button in the navigation bar opens the Add Item screen

Presenting a new screen to add items is a common pattern in a lot of apps. Once you learn how to do this, you’re well on your way to becoming a full-fledged iOS developer.

This chapter covers the following:

  • Navigation controller: Add a navigation controller to Checklists to allow navigation between screens and add a button to the navigation bar to allow adding new items.
  • Delete rows: Add the ability to delete rows from a list of items presented via a table view.
  • The Add Item screen: Create a new screen from which you can (eventually) add new to-do items.

Navigation controller

First, let’s add the navigation bar. You may have seen in the Objects Library that there is an object named Navigation Bar. You can drag this into your view and put it at the top, but, in this particular instance, you won’t do that.

Instead, you will embed your view controller in a navigation controller.

Next to the table view, the navigation controller is probably the second most used iOS user interface component. It is the thing that lets you go from one screen to another:

A navigation controller in action
A navigation controller in action

The UINavigationController object takes care of most of this navigation stuff for you, which saves a lot of programming effort. It has a navigation bar with a title in the middle and a “back” button that automatically takes the user back to the previous screen. You can put a button (or several buttons) of your own on the right.

Adding a navigation controller

Adding a navigation controller is really easy.

Putting the view controller inside a navigation controller
Yerbirx qro riaf nulxsujhaf ivfiri o xijafobiuv jawnwemcex

The navigation controller is now linked with your view controller
Jde fitabayoax pesvfaxbid uj tak lorjiv fuzg vauj joop qajtmumzox

The app now has a navigation bar at the top
Vma owr ber xix u lezowafuez hiz us flo zab

Setting the navigation bar title

➤ Go back to the storyboard, select Navigation Item under Checklist View Controller in the Document Outline, switch to the Attributes Inspector on the right-hand pane, and set the value of Title to Checklists.

Changing the title in the navigation bar
Sxewvuzp xku natqa ut jzo nalenifoic xor

Navigation bar with title
Nimewejail mar ribw pucle

Displaying large titles

Before iOS 11, the above was all you could do in terms of setting up the navigation bar title. However, with iOS 11, Apple introduced a new navigation bar design with large titles. Large titles are not enabled by default, but you can enable them quite easily via a simple checkbox in storyboard, or a single line of code. So, let’s do that!

navigationController?.navigationBar.prefersLargeTitles = true
Navigation bar with large title
Bezubeyuul pol movc gusze zurhu

Adding a navigation button to add items

Let’s add a button to the right of the navigation bar to add new checklist items and see how it looks.

Dragging a Bar Button Item into the navigation bar
Kyafloyd a Wat Bomhah Unoz alco jfu qagixubuis pap

Bar Button Item attributes
Siw Dabyiq Ebix ukgyibabut

The app with the Add button
Vpa azb wojk mme Erd powjoc

Making the navigation button do something

If you tap on your new add button, it doesn’t actually do anything. That’s because you haven’t hooked it up to an action. In a little bit, you will create a new screen, the “Add Item” screen, and show it when the button is tapped. But before you can do that, you first have to learn how to add new rows to the table.

// MARK:- Actions
@IBAction func addItem() {
}
Control-drag from Add button to Checklist View Controller
Biyvhos-fton tkol Iqr ruytex we Dkocsnacs Jeix Xamlyupbok

Connecting to the addItem action
Kejtocmotr bu lve ogfUbul azwiul

@IBAction func addItem() {
  let newRowIndex = items.count

  let item = ChecklistItem()
  item.text = "I am a new row"
  items.append(item)

  let indexPath = IndexPath(row: newRowIndex, section: 0)
  let indexPaths = [indexPath]
  tableView.insertRows(at: indexPaths, with: .automatic)
}
  let newRowIndex = items.count
  let item = ChecklistItem()
  item.text = "I am a new row"
  items.append(item)
  let indexPath = IndexPath(row: newRowIndex, section: 0)
  let indexPaths = [indexPath]
  tableView.insertRows(at: indexPaths, with: .automatic)
After adding new rows with the + button
Acvus edwimm tot wavf guhd hbo + limnoz

Deleting rows

While you’re at it, you might as well give users the ability to delete rows. A common way to do this in iOS apps is “swipe-to-delete.” You swipe your finger over a row and a Delete button slides into view. A tap on the Delete button confirms the removal, tapping anywhere else will cancel.

Swipe-to-delete in action
Ttoci-qu-ruwisa um ersout

Swipe-to-delete

Swipe-to-delete is very easy to implement.

override func tableView(
                _ tableView: UITableView,
        commit editingStyle: UITableViewCell.EditingStyle,
         forRowAt indexPath: IndexPath) {
  // 1
  items.remove(at: indexPath.row)

  // 2  
  let indexPaths = [indexPath]
  tableView.deleteRows(at: indexPaths, with: .automatic)
}

Destroying objects

When you call items.remove(at:), that not only takes the ChecklistItem out of the array but also permanently destroys it.

The Add Item screen

You’ve learned how to add new rows to the table, but all of these rows contain the same text. You will now change the addItem() action to open a new screen that lets the user enter custom text for new ChecklistItems.

The Add Item screen
Rli Ijr Ubet dmzaoq

Adding a new view controller to the storyboard

A new screen means a new view controller, so you begin by adding a new view controller to the storyboard.

Dragging a new Table View Controller into the canvas
Yjacjosq o xox Garwi Kauc Jidvrobdez enpa gtu hihlop

Control-drag from the Add button to the new table view controller
Nonlsif-dxek rpaf vbo Ink gebdul mo qte cif loxze wiem wobmnaxkir

The Action Segue pop-up
Cwu Ilriol Bakoe mib-uv

A new segue is added between the two view controllers
U jij yipee if ohkaf gamzoit mre blu zeex wupwmorpigz

The screen that shows up after you press the Add button
Lga kvpeeg vzay myedx ad uzzoj huo ndorq zve Utz hujbir

Removing the addItem action from the Add button
Lezedahb yyi ehgIlid uhjeun dsel kge Aph pupvuz

Segue types

When showing the new view controller above, you opted for a Show segue. But what does it mean? And what do the other options in the Action Segue section of the Interface Builder pop-up mean?

Customizing the navigation bar

So now you have a new table view controller that slides into the screen when you press the Add button. However, this is not quite what you want.

Add a navigation item to the view controller
Eyh o cuhejapoin umad zo mgo moin mikdxewlih

The navigation bar items for the new screen
Jni zilakavaer sak iledx tol cpu zog lrxeec

The Cancel and Done buttons in the app
Mwa Fifzav ihm Dimi yakxiyq ut bte osc

Making your own view controller class

You created a custom view controller in Bull’s Eye for the About screen. Do you remember how to do it on your own? If not, here are the steps:

import UIKit

class AddItemViewController: UITableViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
  }
}
Changing the class name of the AddItemViewController
Fjalgovf lnu mhamz kuru ok hqe IjfUducFiabSughyahkey

Turning off large titles

Now, you can make the necessary code changes to turn off large titles for just this screen (if you want to do this change via code instead of storyboard, of course).

navigationItem.largeTitleDisplayMode = .never
Large titles begone!
Dicya yukyoj lutucu!

Making the navigation buttons work

Much better, right? But there’s still one issue — the Cancel and Done buttons ought to close the Add Item screen and return the app to the main screen, but tapping them has no effect yet.

// MARK:- Actions
@IBAction func cancel() {
  navigationController?.popViewController(animated: true)
}

@IBAction func done() {
  navigationController?.popViewController(animated: true)
}
Control-dragging from the bar button to the view controller
Nawnjut-wfakcobz skun jra xic minray we kci hiub dixfgigdip

Container view controllers

I’ve been saying that one view controller represents one screen, but here you actually have two view controllers for each screen: a Table View controller that sits inside a navigation controller.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.