Author: Frank Anderson
Last Updated: 22 September, 2022
To get started, click Create a new Xcode project
. With App
selected, click Next
. Name your first app, and make sure your interface is SwiftUI
. Click Next
and then choose a place to store your project. Click Create
and your project should open up.
When you first open Xcode you should see something like this:
Xcode should open your project to the ContentView.swift
file. Inside, you’ll see a struct
named ContentView
of type View
. Inside, is a computed property named body
of type some View
; meaning the body can be any type of view (Text
, Image
, VStack
, etc.). Right now, the body is a VStack
.
All objects in SwiftUI are eventually Views
. Keep this in mind if you ever are trying to return a String
or an Integer
instead of a Text
view for example.
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
}
}
Let’s start by modifying the Text
view. You can add .font(.title)
and .foregroundColor(.green)
below it, just like .imageScale(...)
and .foregroundColor(...)
on the Image
view above it. Your text should now be larger and in green. You’ve written your first SwiftUI code!
body
worksLet’s clear our ContentView
’s body property and start building the foundations of a user interface. We’re going to build one row of a List
that we’ll create later. Your ContentView
should look like this (and Xcode might have throw a ton of errors):
struct ContentView: View {
var body: some View {
}
}
If Xcode is throwing errors, it’s because the body property needs to return a view, but at the moment it’s empty so it’s not returning anything. Let’s fix this.
We want to display more than one item at a time so we’ll need to use some structures which let us combine more than one view into a single view. The most common form of these are Stacks
. SwiftUI has three types of Stack, the HStack
, VStack
, and ZStack
. They let you layout content in Horizontal, Vertical, and Z-direction space.
Since we’re building a row for a list, let’s layout our content horizontally using a HStack
. Add HStack {}
to your body property.
body
Now, let’s populate our layout with some content. We’re going to build a Wollaston’s Bakery catalogue, so let’s think through what this row might need. It’s going to represent an item they offer, and when we tap on the row it will show a detali view with more information about the item.
Helpful information to put on this list row might be an Image to show the type of item, some Text to show the name of the item, and on the far right edge we can show the price.
To our body
property let’s add an Image(systemName: “”)
, Text("")
, Spacer()
, and another Text("")
. Then we’ll walk through each item one-by-one.