iOS Training - iOS Schulung - Swift Training - Swift Schulung
February 13, 2020

iOS Tutorial: Example project "Dice app"

Goal

Build an iPhone app to roll a dice:

Dice app in simulator

Objectives

This tutorial will show you how to:

Requirements

For this tutorial no previous knowledge of Swift / Xcode is required. To develop iOS apps for the iPhone/iPad using Xcode 11, you’ll need a Mac running at least macOS 10.14 Mojave.

Install Xcode and create a new iOS project

  1. Open the App Store app and install the latest Xcode:

    Install Xcode via Mac App Store
  2. Start Xcode and check your Xcode version on the welcome screen:

    Xcode version
  3. If you already know how to create Xcode projects and import image assets, take a shortcut and download the starter project Dice-starter.zip with the images already set up and skip to adding the UI views.

  4. Run Xcode and create a new project with File » New » Project ⌘⇧N. Select iOS » Application » Single View Application:

    File » New » Project » iOS » Application » Single View Application
  5. Configure the project settings:

    • Name the app “Dice”.
    • Use com.example as Company Identifier. This should be a domain name you own to prevent naming conflicts; feel free to use your own domain name.
    • Choose Swift as Language.
    • Choose Storyboard as User Interface technology.
    • Uncheck Use Core Data and Include Tests (which are not needed for this tutorial):
    Project settings Dice
  6. Confirm with Next and choose a folder in which Xcode should create a "Dice" folder for the project.

Import images into the Xcode project

  1. Download assets.zip which contains images for the project and uncompress the archive.

  2. Open Assets.xcassets in the Xcode project and drag the images for the dice into the project:

    Drag folder dice into assets
  3. Add icon_60pt@2x.png and ...@3x.png as iPhone app icon:

    Add an app icon

Edit the storyboard and add UI elements to the view controller

  1. Open Main.storyboard. You'll see the Initial View Controller of the app with an empty View:

    Open Main.storyboard
  2. Use the Library to add a Image View and a Button to the view (hint: you can search in the library by name). Double click or drag it from the library to the storyboard:

    Add Views using the Library
  3. Place them like this:

    Placement UIImageView and UIButton
  4. Select the image view and choose one of the dice images from the Attributes Inspector. Use Editor » Size to Fit content ⌘= to resize the view to the size of the image:

    Dice image for image view
  5. For the button, set "Roll!" as title:

    Text UIButton

Create layout constraints

To center the views on all device sizes, use a Stack View and Auto Layout constraints:

  1. Select both views and use Embed in » Stack View to create a Stack View that stacks both views vertically:

    Embed in » Stack View
  2. Use Add Alignment constraints to create constraints that center the view horizontally and vertically in the container:

    Add Alignment constraints
  3. Use View as to switch to another device size and check if the layout still looks good:

    Select device size

Handle button taps with actions and outlets

  1. Select the View Controller object and open the Identity Inspector. The class specified here contains the code responsible for managing the views of the controller:

    Custom class in identity inspector
  2. Open the assistant editor to show the code next to the storyboard editor:

    Assistant Editor
  3. Drag with Ctrl pressed down / with the right mouse key from the Image View into the code of the class to create a new Outlet property that can be used to refer to the view in the code:

    Create an outlet

    Name the outlet diceImageView:

    Outlet name
  4. Drag with Ctrl pressed down / with the right mouse key from the Button into the body of the class to create a new Action method that is called when the Button is tapped:

    Create an action method

    Name the action method rollDice:

    Action name

Writing code to roll the dice

  1. The view controller class should look like this now:

    class ViewController: UIViewController {
        
        @IBOutlet weak var diceImageView: UIImageView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    
        @IBAction func rollDice(_ sender: Any) {
        }
        
    }
    
  2. Inside the rollDice method, use the range feature of Swift to generate a random number. Keep the generated number as a constant declared with let:

    @IBAction func rollDice(_ sender: Any) {
        let number = (1...6).randomElement()
    }
    
  3. Check the returned type by -clicking the number constant:

    Return type optional

    The type is an Optional type Int?. In this case, the method always returns a value, but randomElement() could return nothing (nil) if it is called on an empty list.

  4. Use the force unwrap operator ! to unwrap the optional - this can be used here because we can be 100% sure that there will always be a value and the method will never return nil:

    @IBAction func rollDice(_ sender: Any) {
        let number = (1...6).randomElement() !
    }
    
  5. Load the image using UIImage. You can use \(...) to insert a value into a string and load an image by name (the images are named dice-1, dice-2, ...):

    @IBAction func rollDice(_ sender: Any) {
        let number = (1...6).randomElement()!
        self.diceImageView.image = UIImage(named: "dice-\(number)")
    }
    

Running the app in the Simulator

  1. Select an iPhone Simulator for the Scheme and hit Run ⌘R:

    Select scheme
  2. The app starts up in the Simulator - test to roll the dice:

Dice app in iPhone simulator