First iOS App – ECTS Calc

About month ago I’ve made a promise to write next post in April. To fulfill this promise I will show you how easily you can create your own iOS application.
Every great tutorial starts with hello world example so I’ve decided to start this series with a simple application for the beginners. My purpose is to show you how quick and fun iOS development can be. In future posts i will dive into details, good practices etc. , so be patient and treat this one as a warm-up. 🙂

Prerequisites

In order to start creating your first app you’ll need a certain set of tools:

  • Computer with macOS system installed (unfortunately iOS is a very closed platform and Windows OS users won’t be able to build iOS apps)
  • Apple Developer account – you can create it here. If you’re not going to publish applications in AppStore, a free membership will be sufficient for you.
  • Xcode 9.3 IDE (or higher) – you can download it from here

ECTS Calc

As an example of a simple iOS application, I will create a calculator for ECTS credits. For all of you who aren’t familiar with this acronym, ECTS stands for “European Credit Transfer and Accumulation System“. It may sound complicated but in higher education system it requires from every student across EU to collect 60 ECTS points per year. It becomes really relevant for students when they cannot collect them and they must pay money for taking again courses which they couldn’t pass. At the Lodz University of Technology, it’s on average 55 PLN per point. I wish that none of you will need this calculator but real life shows that it can be very useful tool. 🙂

1. Create new Xcode project

2. Pick Single View App

3. Provide application info

In this step we must provide basic information like:

  • Project name
  • Team – Apple Developer team which in free membership is Personal Team
  • Organization Name
  • Organization identifier which usually is reversed domain like in Java projects.
  • Language – In my posts I will only cover Swift language.
  • Core data – SQLite data persistence
  • Include UI/Unit Tests – when checked, it automatically creates unit tests targets.

4. Choose project directory

After the wizard is finished we have 6 files in our project directory:

  • AppDelegate.swfit – In this file we can manage application lifecycle events.
  • ViewController.swift – View controller class which will hold all application logic. It’s worth to mention that in production apps it is considered as a bad practice but it’s good for educational purposes.
  • Main.storyobard – User Interface builder is a graphical tool which enables us to create quickly and easily even more complicated views. It is also possible to create all views in the code but is less common than using storyboards.
  • Assets.xcassets – Assets catalog which holds all of the graphical assets like images.
  • LaunchScreen.storyboard – In this file we create splash screen which is shown at the startup before the application is completely loaded.
  • Info.plist – configuration file which defines application version, name etc.

5. Create User Interface

When you click on Main.storyboard file, interface builder shows up. It’s very complex tool, but basic components which you must be aware of are:

  1. View hierarchy window which helps to understand how views are organized.
  2. Storyboard editor which enables you to create user interfaces using drag and drop.
  3. View configuration that shows all possible configuration options for selected UIView.
  4. Object library with all available UI components. If you want to use any of them, just drag and drop selected item on storyboard.

1. Add image asset

On the first (and only) screen of application I will use an image as a header so before that, I need to add this image to assets. To achieve this I only need to drag my image from Finder window to Assets.xcassets catalog. From now I can use that image across the whole project just by referencing it by its name “ects_logo”.

2. Change background color

We must to go back to Main.storyboard file and then click on View Controller window which is only visible UI component so far. On the right side of screen background, the color picker will show up. I will change this color from white to dark red.

3. Add UIImageView to storyboard

After you drop imageView on the storyboard, click it once to show the context menu. Type in “ects_logo” which is a name of our asset in the “Image” text field. Under this text field, there is also “Content Mode” combo box in which we must change the current mode from default “Scale To Fill” to “Aspect Fit”. This change will guarantee us that image will keep its aspect ratio.

4. Add UITextField to storyboard

Similar to UIImageView we drag and drop UITextField on the storyboard and then set “Placeholder” field to provide a hint about what type of data user should enter. The second parameter which I’ve changed is a keyboard type, it should be “Number Pad” to ensure numeric input. It won’t prevent the user from typing all incorrect values but in this post, I will skip this topic. Just keep it in your mind that in production apps It won’t be sufficient solution.

5. Add UIButton to storyboard

Last UI component is UIButton, which will trigger calculating amount of money to pay for missing points. In this case, I’ve changed default title from “Button” to “Calculate”, Text color to dark gray and background color to white.

6. Setting up constraints

One of the most powerful tools for creating User Interface for iOS platform is the auto layout. Instead of calculating dimensions of view for every possible device we just set necessary constraints.

The first step for our layout will be to close all of the current components in a container called UIStackView. It will help in distributing evenly all of the elements. In order to achieve this, we must press command + shift and select all of the components. When all elements are selected press stack button on the bottom of the screen.

After this action, all elements should be closed in stack view container. It’s very easy to maintain even many elements. For example, if we want to set some space between elements, we don’t have to set padding for each element. There is “Spacing” option which provides us such functionality. Set this value to 40 to distribute those elements.

Click on UIStackView and click Constraints button which is situated on the bottom of the screen nearby “Stack” button. Select side constraints and set them to 70 points, then press “Add 2 Constraints”.

Click once more on stack view and click “Alignment Constraint” button on the bottom of the screen. Pick “Vertically in Container” and press “Add 1 Constraint button”.

If you managed to finish all of these steps, you just created your first iOS User Interface! 🙂

7. Connect IBOutlets

Comparing to Android development referencing UI elements in code is extremely easy.
Just click split view button, which will show storyboard UIViewController on the left side and UIViewController swift class on another.

Next step is to click UITextField in hierarchy view and press Control button. This will make possible to drag it on Swift class file. When pop-up window will show up, choose “Connection” and pick Outlet. You must fill “Name” field because this will be also the name of this element in code.

Next step is to connect button click action. It is very similar to connecting text field but we must choose “Action” instead of “Outlet” connection type. There is also a difference in the name field because it will be the name of the method instead of the variable. This method will be invoked every time user press calculate button.

6. Implement logic of calculator

As you can see whole logic is pretty simple and it’s no longer than 50 lines of code.
I will guide you through this code line by line.

  • Line 13: IBOutlet provides us the reference to UITextField component.
  • Line 14: Immutable variable which stores what is a cost of one missing ECTS point.
  • Line 20: calculatePressed method which runs every time user taps calculate button
  • Line 21: In this line “missingPointsText” variable stores text from UITextField. Because text property can be nil there is “??” operator. In this case, operator sets empty String value if it found nil.
  • Line 23: “guard let” is also a way to safe unwrapping optional values. If Integer cannot be constructed from missingPointsText variable (it returns nil) else block is executed. It is a very clean solution for checking if variable crucial for our logic isn’t nil.
  • Line 28: costOfMissingPoints variable stores result of number of ECTS points and it’s cost multiplication.
  • Line 30: When calculated amount of money is greater than zero then we show user alert with this amount.
  • Line 31: You may be curious why there are brackets inside of the message.
    \(costOfMissingPoints) “. It is called String interpolation which is used to place value of given variable inside String.
  • Line 32: If the amount of money is negative it means that user typed in a negative number of ECTS points which is an invalid value.
  • Line 34: If else block is executed it means that student completed all required ECTS points and he doesn’t have to pay any money.
  • Line 39: This method shows an alert popup with ECTS calculator message.

Summary

I hope that the recipe for a simple iOS application which I presented helped some of you to dive into iOS development. I’ve realized that next topics shouldn’t be based so much on user interface operations like this one. Text and images aren’t so great medium for such type of content. Next time I will try to avoid it or record some video to help you out understand what is happening.

Complete ECTS Calc application is available on my GitHub repository.

As I’ve mentioned earlier I will be happy if you provide me any kind of feedback. It will help me improve next posts.

I’ll be back! 🙂