2️⃣Getting Started with SwiftUI
Fall 2023 | Vin Bui
Last updated
Fall 2023 | Vin Bui
Last updated
Enter the name of our app. In this example, we will be calling our app Sample
.
Choose SwiftUI for the Interface.
On the left side of Xcode, we shoul see a list of files in the directory. This is known as the project navigator.
SampleApp.swift
contains code that is executed when we launch our app. If we want to create something when we launch our app and keep it throughout the app’s lifetime, we will write it here.
ContentView.swift
contains code that defines the UI for our app. Most of our code will be written in a file similar to this.
Assets.xcassets
is a catalog that contains the app’s images, icons, colors, and more.
There is a group labeled Preview Content
that contains a single file called Preview Assets.xcassets
. This is a catalog similar to Assets.xcassets
above, but for previewing the UI which will be explained next.
On the right side of Xcode, we should see a canvas containing a preview of the app. If not, go to the Editor menu and select Canvas (alternatively ⌥ ⌘ ↵). The device that is shown on the preview depends on the device we select at the top center of Xcode. Because the preview is updated live, errors within our code can cause the preview to pause. To resume, we can click Resume in the canvas or even better, use the shortcut: ⌥ ⌘ P
ContentView.swift
To use all of the functionality provided by the SwiftUI framework, we must import it using import SwiftUI
. This is similar to how we import other frameworks such as UIKit, MapKit, etc.
Next, we create a struct called ContentView
that conforms to the View
protocol. The View
protocol is a type that represents our app’s UI and provides modifiers to configure our views. If we want to draw anything on the screen using SwiftUI, then it must conform to the View
protocol.
Inside of the ContentView
struct, there is a required property called body
that has the type of some View
. What this type really means is that this property will return something that conforms to the View
protocol. Later on, we will learn that the actual return type of this property is very complicated (could be 1000+ characters) so providing a general return type of some View
means we can ignore that. The body
property is the only requirement needed to conform to the View
protocol.
Starting in iOS 17, the syntax for the preview is different:
The functionality is the exact same as it was in previous iOS versions.