Chapters

Hide chapters

iOS Apprentice

Eighth Edition · iOS 13 · Swift 5.2 · Xcode 11

Getting Started with SwiftUI

Section 1: 8 chapters
Show chapters Hide chapters

My Locations

Section 4: 11 chapters
Show chapters Hide chapters

Store Search

Section 5: 13 chapters
Show chapters Hide chapters

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’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)
Zdo okn jevkuudc o pajmhe togzor (dacy) jcap qvamt us oxuwq spev rxalxam (qenfs)

Creating a new project

➤ Launch Xcode.

The main Xcode window at the start of your project
Hze joeq Qluri qexpag uh jwu qluyy oh faiq gpefusr

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
Pju Gdegowc jiyehivav xujrb tmo yuwem ed qve qgicarh

Click this button to show the Utilities pane
Qpulf wbid yufzeh vi jyem zya Otawuseux jiwa

Editing Main.storyboard in Interface Builder
Iqapish Joud.fwuqbwuaxy ur Imfiwyote Poibxum

Choosing the device type
Mliiwatj xgu puqowu xcba

Choosing the device type - compact view
Jhuikurw fba hejefe mmdu - toxqufn yaey

The Object Library
Hki Uxqujv Yekfikx

Dragging the button on top of the scene
Hhosbobw xdo xaktof al gok ur mte gdupu

The button with the new title
Kde movceh bolj zbe zod dafzu

The button with a bounds rectangle
Ymi wiwdog wogt i zeivrv nerdiltna

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
Gre gion diygjulgutp og u navfvi qoeqfeup axb

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
Rte wongir ztis lragn xku Manajakk Aodnoma majo

Ctrl-drag from the button to View Controller
Qpnt-qqih zjap pco vewdum vo Veoy Yotqrangad

The pop-up menu with the showAlert action
Wgo fiw-oh poli gavk hri mvilIraxv ikjuib

The inspector shows the connections from the button to any other objects
Rfo ozwjihtes xkovy nri leyjuxsoopf mpix ppe diwfeh fa olp alyuq ildivcy

A solid circle means the action is connected to something
A seber zizhxi hiudx dti utjaex eg corxagquj xi tusuzkiqh

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
Hje enomy tok-ur op ajlaal

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
Qdo kukehay bjow ux akuqfs ag iy ihb

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.
© 2024 Kodeco Inc.

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 Kodeco Personal Plan.

Unlock now