Skip to content

First application (SwiftUI)


Prepared and tested with Xcode 13.3.1 and Swift 5.3 (last update: 2022-04-28)

In this part you will learn how to create new SwiftUI project and how to use Xcode to develop it. At the end you will have your first SwiftUI application.

Table of contents


Start Xcode and set up a project

Before start, please note that Xcode is a huge appplication taking into account both its logic and physical property (downloaded file close to 11GiB, application close to 37GiB). Additionaly, Apple changes and adds something to it every year. Althouh I do my best to present most actual screens and description, it might happend that real Xcode differs somehow compared to my description. Don't worry about it — if you know what you are looking for, deffinitely you will find it maybe under the different name, moved to different option or in different menu. Keep calm and take a moment to find what you are looking for. This text is updated for Xcode Xcode 13.3.1 and Swift 5.3.

After successful Xcode installation, which is time consuming process but not very complicated and you can complete this using App Store app (or get it via Apple developer website which I do not recommend at the first time), search for the Xcode icon and clik on it to run it:

You’ll see this Welcome window:


The first time you open Xcode after installation, you’ll see Install additional required components? window. Click Install and enter your Mac login password in the window that appears. When this installation process finishes, you might have to open Xcode again.

If you don’t want to see this window every time you open Xcode, uncheck Show this window when Xcode launches. If this window is missing, you can manually open it from the Xcode menu Window / Welcome to Xcode or press Shift-Command-1.

Click Create a new Xcode project. Or, if you want to do this without the Welcome window, press Shift-Command-N or select File / New / Project... from the menu.

In a Choose a template for your new project window select iOS / App and click Next:


When you create a new project, the project template screen includes options to select how the app project is to be implemented. There are specific Apple platform available (such as iOS, watchOS, macOS or tvOS), or you can simply create a multiplatform project. When you select a platform specific option you will have the choice of creating either a Storyboard (UIKit) or SwiftUI based project.

A multiplatform project allows you to make an application for multiple Apple platforms with the minimum of platform specific code. Even if you plan to initially only target iOS the multiplatform option may be a good choice since it provides the flexibility to make the app available on other platforms in the future without having to restructure the project.

You will see the project options window:

You can skip Team field if you want, but all other fields must be filled with text:

  • For Product Name type SwiftUI iOS First Application.
  • For Organization Identifier you can specify whatever you want but keep in mind note given below.


    The Organization Identifier is typically the reversed URL of your's website, for example in my case this is pl.fulmanski. Following this convention, you have guarantee (saying the truth, high probability but without any guarantee) that Organization Identifier concatenated with Product Name will give you a globally unique name. It is important if you have plans to upload your application to App Store because it serves to uniquely identify the app within the App Store when the app is published. This name is also used when creating provisioning profiles and certificates to enable testing of advanced features of iOS on physical devices.
  • For Interface, select SwiftUI.
  • For Life Cycle, select SwiftUI App.
  • For Language, select Swift.
  • Uncheck the checkboxes.

When you finish, click Next and after selecting saving location finally your new project appears with the default layout for SwiftUI development displayed:


Gain familiarity with how Xcode works in SwiftUI mode

The Xcode has three main panes: Navigator, Editor and Inspector. When you run the app the Debug Area opens below the Editor; you can hide or show it with Shift-Command-Y. Additionaly to this, when you’re viewing a SwiftUI View file in the Editor, you can view the preview canvas side-by-side with the code (press Option-Command-Return to show or hide it or select Editor / Canvas from main menu).

You can hide or show the Navigator and the Inspector with the toolbar button just above it. The Debug Area has a hide button in its own toolbar. Being more precise, you will find more show / hide button in the Debug Area as it is dividded into two parts: variable view (displays variables within the app at the point that the app crashes or reaches a debugging break point) on the left and console view (print output and messages from the running app) on the right. You can also hide any of these three panes by dragging its border to the edge of the Xcode window.

Developing iOS application you’ll spend most of your time working with a .swift files.
A newly created iOS app includes two files named [APP_NAME]App.swift (in this case SwiftUI_iOS_First_ApplicationApp.swift) and ContentView.swift which, when selected from the project navigation panel, will appear within Xcode both in text and preview part of editor pane. If preview is empty, click the Resume button:

and wait patiently until you see screen similar to given below:


The preview canvas

Xcode has experienced significant changes over the years but as the most innovative aspect personaly I perceive is live preview of UI. The preview canvas provides both a visual representation of the user interface design and a tool for adding and modifying views within the layout design. What is really nice, selecting a view in the canvas will automatically select and highlight the corresponding code in the code editor, and vice versa. When you change your code, it reflects your UI, and vice versa: when you "mainpulate" your UI components at the same time code reflects your actions. At the same time attributes for the currently selected item will appear in the attributes inspector panel.

The canvas may also be used to perform live testing of the running app without the need to launch an iOS simulator. Because every change in code are immediately reflected within the preview canvas, to avoid this continual updating the preview will occasionally pause live updates. When this happens, the Resume button mentioned earlier will appear. It's enough to click it to resume updating the preview.

There are three areas of preview:

  • The main canvas area represents the current view as it will appear when running on a physical device.
  • At the top you will find the preview toolbar.
  • The pin button is located at the left bottom corner.


The pin button

A you know, when you select a view file in the project navigator, both the code editor and preview canvas will change to reflect what you have just selected.

It is likely that your application will consist of more than one view in addition to the default ContentView.swift file. The more views you have the more probable is that you may want to see in the preview canvas the user interface layout for one view while editing the code in a different file. Very commpn situation is when the layout from one file is dependent on or embedded in another view. The pin button "pins" the preview to the canvas so that it remains visible on the canvas even after you select source file of a different view.


The preview toolbar

The preview toolbar offers five buttons you can use to change preview panel:

Starting from the left these are:

  • 1: Lieve preview button Click this button to see user interface in the running version of the app instead static which is default mode.
  • 2: Preview on device Click this button if you rather prefere to make a preview on an attached physical device.
  • 3: Rotate preview Clik this buttonto change view orientation from vertical to horizontal and vice versa.
  • 4: Inspect preview Clik this button to change properties of the canvas, for example the devce type, mode (light or dark), or dynamic text size.
  • 5: Duplicate preview Click this button to display multiple preview canvases. Below you see an example of two previews at the same time: for iPhone SE and iPhone 13 mini. Notice how code reflect this changes changing contents of previews in ContentView_Previews structure.


The code


The ContentView structure

Initially, just after creation, the heart of your project, at least its visual interface, is in ContentView.swift file:

Inside this file you will find two structures:

  • ContentView,
  • and ContentView_Prewiews.

The name of the first structure matches the name of the file. Nothing bad happens if they’re different, but most developers follow and expect this convention.

When you look at it you will notice that ContentView conforms to View protocol. The required component of the View protocol is the body computed property, which returns a View, more precisely: some View. If you are confused with existence of the some keyword, please refer to my book More Swift by examples.

Everything you do in SwiftUI is focus around views. You add new views, customize existing views with modifiers, add logic and ways of interacting with their states and bind to data. You can perform all of this tasks either in text editor or by arranging visual components and setting appropriate values in properties windows as both reflects any change immediately. Although the visual editing capability seems tempting because of its simplicity and intuitiveness, most changes are usually made in text mode for the sake of speed and better control of what you do.

  • The most simple interaction you can take is modifying existing view. Completing this in text editor is as simple as adding new call to a methods. For example, to change default font you can replace the following code in ContentView.swift file:

    with:

  • Another option to do the same is selecting the Text view in either the code editor or the canvas, then selecting the Attributes inspector. Next click in the Add Modifier field and wait a few seconds until the modifiers menu appears:

    An entry for selected modifiers subsequently appear in the inspector where you can configured them the required properties:

    • From modifiers select Font:
    • From Font attributes select Font list:
    • From liste select Large Title:
    • Do the same for Color and select Yellow:
    • Finall result is as previously:
  • You can do this even faster and open the Attributes inspector pop-up window with Control-Option-click:

  • An alternative to this is to make changes to the views by dragging and dropping items from the Library panel. You can display this panel by clicking on the toolbar button:

    You will see the Library panel:


    The Library panel is transient and will disappear either after you make a selection, or click outside of the panel. If you want to keep the panel displayed, hold down the Option key when clicking on the Library button.

    At the top of the Library panel you will see the toolbar allowing you to switch to different categories:

    • 1: Views library -- views like buttons, labels, horizontal stack etc.,
    • 2: Modifiers library -- modifiers,
    • 3: Snippets library -- commonly use code snippets,
    • 4: Media library -- media resources,
    • 5: Color library -- color resources.

    To apply element from the library panel you simply select it, drag it:


    and drop it at the correct place:


The ContentView_Previews structure

Below ContentView is a ContentView_Previews structure:

This structure defines what appears in the canvas on the right of the code editor. By default, the preview canvas shows the user interface on a single device. To preview on other device models you can use the preview toolbar as I described it earlier. Sometimes it's much faster to acomlish this with code -- for example you can change ContentView_Previews contents to:


Creating and using your own SwiftUI view

In most UI libraries everyting you see on a screen is a window, widget or as it is named in SwiftUI: a view. No matter what you call it, the idea is to have one family of object you can freely arrange to obtain almost wahtever you want. Everything is a view and you may be scared of how many such views exist even for a simple UI. But it's compiler job to create efficient machine code to prevent your app’s performance from suffer. Apple encourages you to create as many (sub)views as you need, to avoid redundancy according to DRY (Don’t Repeat Yourself) principle helping keep your code manageable.

Even at the begining of your SwiftUI journey you can try to create your first view. It's not complicated and you will do this in steps.

  • Step 1
    In the Project navigator, select SwiftUI iOS First Application folder, right-clik on it and select New File... from the pop-up menu. Alternatively, after selecting the folder, you can press Command-N or select File / New from main menu. Whatever option you choose, you will see Choose a template for your new file window:

    Select iOS / User Interface / SwiftUI View and click Next.

  • Step 2
    In the next window specify a file name as CustomView and clik Create:

    If the file appears in the projct navigator where you don't want it, you can drag it to more convenient location for you:

  • Step 3
    Change the contents of the CustomView.swift file:

  • Step 4
    In ContentView.swift replace existing Text view with:

    Immediately you should see effect:


    If not, click Resume or press Option-Command-P to refresh the preview.


Running the app on a simulator

Live preview is a great feature of Xcode and SwiftUI but not everything can be tested this way. And even if, then there will certainly be a moment when you want to see how your application works on a real device or simulator (by the way, the simulator is really great and you can easily use it instead of real hardware).

Click the run destination field:

and select your destination iPhone model -- it can be either real device (in my case there is no device) or any of available simulated models:

Press Command-R or click the run button:

The first time you run an app on a simulated device, it starts as real device from an "off" state, so you’ll see a loading indicator and you "device" needs some time to start up. But dont be afraid, this process only takes place until you quit the Simulator app. Otherwise simulated device stays in "active mode", so you won’t get the startup delay any more even if you run a totaly different project on it.

After the simulated device starts up, your app is launched and you will see it running:

Clicking on the stop button (B) will To terminate the running app press Command-. or click the stop button:


Summary

I don't know if you have noticed, but you have just created your first SwiftUI. Congratulations! It wasn't difficult, was it? I hope you will continue reading next parts.

The key points of this part are:

  • How to create iOS project in Xcode.
  • What a preview is and how the preview canvas works.
  • General understanding of the ContentView and ContentView_Previews structure.
  • How to create simple SwiftUI view.
  • How to run your app either on simulator or real device.