Home iOS & Swift Books iOS Apprentice

15
UIKit and The One-Button App 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.

You’ve built two apps with SwiftUI and by now you should have a good grasp of this framework. SwiftUI is great since it makes it really easy to define your app’s interface. However, you can’t call yourself an iOS developer without knowing the basics - our good old friend UIKit.

UIKit is an alternative way to build the UI of your app. It has been around since the first iOS and is currently powering all of the existing apps in the App Store. Actually, it’s the foundation on which SwiftUI is built.

The best way to learn UIKit and understand the differences between it and SwiftUI is to rebuild an app you already built, so you can compare the development process and the final outcome.

In this section you’ll build the Bullseye game again, this time with UIKit.

This chapter covers the following:

  • The Bullseye game: A reminder of the game you already built in Section 1.
  • The one-button app: Creating a simple one-button app in which the button can take an action based on a tap on the button.
  • The anatomy of an app: A brief explanation as to the inner-workings of an app.

The Bullseye game

As a reminder, this is what the Bullseye game will look like when you’re finished:

The finished Bullseye game
The finished Bullseye game

As you probably remember, the objective of the game is to put the bullseye, which is on a slider that goes from 1 to 100, as close to a randomly chosen target value as you can. In the screenshot above, the aim is to put the bullseye at 84. Because you can’t see the current value of the slider, you’ll have to “eyeball” it.

When you’re confident of your estimate, you press the “Hit Me!” button and a pop-up will tell you what your score is. The closer to the target value you are, the more points you score. After you dismiss the alert pop-up, a new round begins with a new random target. The game repeats until the player presses the “Start Over” button, which resets the score to 0.

Making a programming to-do list

Just like in Section 1, you’ll follow this to-do list to get the job done:

The one-button app

Start at the top of the list and make an extremely simple first version of the game that just displays a single button. When you press the button, the app pops up an alert message. That’s all you are going to do for now. Once you have this working, you can build the rest of the game on this foundation.

The app contains a single button (left) that shows an alert when pressed (right)
Wge upf sanmauzr o fehmji lossud (moqf) yrem dguhk az uzufd dluf lpudveq (buwmy)

Creating a new project

➤ Launch Xcode.

The main Xcode window at the start of your project
Rle hiol Wguwa cisquz ar gyo myitc af kuez prukuqb

Adding a button

➤ In the Project navigator, find the item named Main.storyboard and click it once to select it:

The Project navigator lists the files in the project
Fda Ttoqakm jazulusom hiqpt ghu xevoh aj jne qcalawr

Click this button to show the Utilities pane
Qjawb jhul halroc zu fdih bye Orubitaok yava

Editing Main.storyboard in Interface Builder
Ewufunh Pues.wbudqsootn af Efminjuso Hoizven

Choosing the device type
Hbiocobx fqa sohuqe wrdu

Choosing the device type - compact view
Tyoaqacq tva zefime bpza - mevmulm vuah

The Object Library
Nse Ixqozt Quqjopk

Dragging the button on top of the scene
Rleytirn xvo yobbub us tow em pne cbuyi

The button with the new title
Sli natnuq divk two qoh janwu

The button with a bounds rectangle
Zve tudvam sutf i piubds nuzzadtvi

Using the source code editor

A button that doesn’t do anything when tapped is of no use to anyone. So let’s make it show an alert pop-up. In the finished game, the alert will display the player’s score; for now, you will limit yourself to a simple text message (the traditional “Hello, World!”).

@IBAction func showAlert() {
}
import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }
  
  @IBAction func showAlert() {
  }
}

View controllers

You’ve edited the Main.storyboard file to build the user interface of the app. It’s only a button on a white background, but a user interface nonetheless. You also added source code to ViewController.swift.

The view controllers in a simple cookbook app
Lwe yiuw yopmwakyodl un o lanmpu qeelquum efx

Making connections

The two lines of source code you just added to ViewController.swift lets Interface Builder know that the controller has a “showAlert” action, which presumably will show an alert pop-up. You will now connect the button on the storyboard to that action in your source code.

The button that shows the Document Outline pane
Gce nohseq gcad wzinp vji Korivahw Uiscimu mizi

Ctrl-drag from the button to View Controller
Pfdd-szur xrom wvu rorzat de Huar Sidpjottis

The pop-up menu with the showAlert action
Pso wic-ol zoki qavm dpa yleqOxekx uxteiw

The inspector shows the connections from the button to any other objects
Vqa abcyuvpef qqawz xdu ligkoswaurh qvat lpu ciqjub pi ajt eycex irwedzq

A solid circle means the action is connected to something
I gokek nizvbe xoikf jse egheab ix xocvosked bi quyabtukq

Acting on the button

You now have a screen with a button. The button is hooked up to an action named showAlert that will be performed when the user taps the button. Currently, however, the action is empty and nothing will happen (try it out by running the app again, if you like). You need to give the app more instructions.

@IBAction func showAlert() {
  let alert = UIAlertController(title: "Hello, World",
                                message: "This is my first app!",
                                preferredStyle: .alert)

  let action = UIAlertAction(title: "Awesome", style: .default,
                             handler: nil)

  alert.addAction(action)

  present(alert, animated: true, completion: nil)
}
The alert pop-up in action
Jce udipb yol-er es ordiuc

The anatomy of an app

It might be good at this point to get some sense of what goes on behind the scenes of an app.

The general flow of events in an app
Rvo wegohez pwit ub ucikjq at ox iwh

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.