Introduction to SwiftUI

Jun 20 2024 · Swift 5.10, iOS 17.3, Xcode 15.3

Lesson 01: Organizing a SwiftUI App

SwiftUI App Walk Through

Episode complete

Play next episode

Next
Transcript

Intro

Hey there, fellow developers! Are you ready to learn how to build amazing apps using Apple’s SwiftUI framework? In this demo, you’ll dissect the key building blocks of any SwiftUI app: the App structure, scenes, and views. Get ready to explore these concepts hands-on as you bring an exciting app idea to life!

Create an Xcode Project

Alright, it’s time to dive in! Because you’re building this app from the ground up, the first step is to create a new Xcode project. Follow along and explore the organization of a SwiftUI App.

Don’t feel you need a deep understanding of any code you see in this episode. All that’s important at this stage of the course is that you get a general idea of what’s going on.

Start Xcode and ensure you’re running Xcode 15 or later. I’m using version 15.2. You might be running a more recent version than that. That’s okay. As long as it’s Xcode 15 or later, you should be fine.

Click the button here that says, “Create a new Xcode project”. Select the template iOS application app and click “Next”.

For “Product name”, enter “ColorPicker”, all one word. For “Team”, leave that as whatever the default is for you. For “Organization identifier”, enter something unique, such as “com.your name” or “com.your company name”, and leave everything else as the default. This is called “reverse domain” naming.

The interface should be SwiftUI, the language should be Swift, and all these should be unchecked. Click “Next” and choose a location to save it. I’m going to save that on the desktop.

This has created some starter code for you. On the left is the navigator panel. It currently lists all the project files, so this tab is aptly named the “Project navigator”. There are other navigators up here, but you’ll use this one most.

So, you’ve got your project set up; now, it’s time to develop a better understanding of the SwiftUI App structure.

The App Struct

You’ll kick things off with the heart of your SwiftUI app - the App structure.

The first you’ll look at is a file called ColorPickerApp.swift, so go ahead and click that to open it. Then, close the navigator with the button in the upper left or the keyboard shortcut Command + 0.

This file is the App struct, and it’s the central building block that defines your SwiftUI application. Here’s where you’ll define the top-level scenes that comprise your app’s navigation backbone. Every SwiftUI app must have one, and only one, main App struct.

Here’s a code snippet.

import SwiftUI

@main
struct ColorPickerApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

And here’s a breakdown of that code: — Line 0: import SwiftUI: At the very top, you import SwiftUI. That says, “I want to be able to use the SwiftUI framework in this file.”

Line 1: @main: This little attribute is incredibly important. It tells the system, “This is where the app starts running. Look for a structure called ‘ColorPickerApp’.”

Line 2: struct ColorPickerApp: App: This line says you’re defining a structure named ‘ColorPickerApp’, which conforms to the ‘App’ protocol. Remember, protocols in SwiftUI are blueprints. In this case, the ‘App’ protocol says you must do one essential thing. …

Line 3: var body: some Scene: This is where you fulfill the requirement of the ‘App’ protocol! The body property asks, ’What kind of scenes and content are in your app?” The some Scene part means you have flexibility in defining those scenes.

Line 4: WindowGroup { ... }: You’re using a ‘WindowGroup’ scene; this is the standard way to create a typical app’s main window.

Line 5: ContentView(): Inside the ‘WindowGroup’, you’re placing a view called ‘ContentView’. This is the primary screen your users will see when they launch the app.

Views: The Visual Building Blocks

Next, you’ll look at the “ContentView.swift” file, so click that to open it. Then, close the navigator with the button in the upper left. Now comes the fun part.

This code defines something called ‘ContentView.’ In SwiftUI, views are the building blocks of everything you see on the screen.

Views like ContentView are where you add text, images, buttons — all the elements the user sees and interacts with.

Look at this code snippet:

struct ContentView: View {
  var body: some View {
    VStack {
      Image(systemName: "globe")
        .imageScale(.large)
        .foregroundStyle(.tint)
      Text("Hello, world!")
    }
    .padding()
  }
}

#Preview {
  ContentView()
}

Here’s what’s happening in it: — Line 0: struct ContentView: View {: You create a structure named ‘ContentView’ that follows the rules of being a SwiftUI view.

Line 1: var body: some View {: This is the heart of your view! The ‘body’ is where you describe what it should look like. That some View part means you can be flexible about what goes inside.

Line 2: VStack { ... }: You use a ‘VStack,’ which is short for ‘Vertical Stack.’ This is like an invisible container to arrange things from top to bottom.

Line 3: Image(systemName: "globe"): You place an image in the stack. SF Symbols gives us access to loads of built-in icons. Here, you grab a globe icon.

Line 4 & 5: .imageScale(.large) .foregroundStyle(.tint): Here, you use view modifiers to make the globe bigger and give it a tint color so it’s easier to see.

Line 6: Text("Hello, world!"): Add the classic ‘Hello, world!’ text under the image.

Line 7: .padding(): Finally, a bit of breathing room! This adds padding around everything inside the stack.

Line 8: #Preview { ContentView() }: This section is all about your preview. You basically say, “Show me a preview of this ‘ContentView’ thing I just made!”

The magic of SwiftUI is that you can nest and combine views to create beautiful and complex layouts with ease. Now, you’ll see how to create a simple view hierarchy.

A Simple View Hierarchy

It’s time to put all these pieces together! You’ll see how the app structure, your choice of scenes, and the arrangement of views come together to define the app’s overall flow and appearance. Get ready to witness how changes in one place ripple through the structure.

Now, make some changes to your ‘ContentView’ and see how the app evolves. Remember, SwiftUI is all about building interfaces piece by piece!

Step 1: A New Image

— First, replace that globe icon with an image of your own. I’ve got a file called “MyCat” in my project. Ensure you’ve added your image to the Asset catalog before going any further.

— Notice how the preview updates? Be sure your image shows up. Now, images can be all sizes, so add .resizable() after the image. This tells SwiftUI to make the image fit nicely into the space it has.

Step 2: Welcome Message

— Under the image, include a welcome message. Add a new line and type Text("Welcome to My App"). See it pop up in the preview!

— That’s a bit small. Make it stand out with .font(.largeTitle). Fonts are a great way to style your text.

Step 3: Adding a Button

— Now, how about a button? Below the text, add Button("Next") { }. A button needs a label — that’s the ‘Next’ part — and a curly brace section where you’ll put the code to run when the button is tapped.

— Right now, the button doesn’t do anything, but you’ll change that later.

The Wrap-Up

Take a look! You’ve gone from a simple ‘Hello, world!’ to something more like a real app. See how each change updates the preview? This is the beauty of SwiftUI — you build and tweak and see the results instantly.

struct ContentView: View {
  var body: some View {
      VStack { // A vertical container view
          Image("myImage")
              .resizable()
          Text("Welcome to My App")
              .font(.largeTitle)
          Button("Next") {
              // Action to perform
          }
      }
  }
}

Outro

And there you have it! You’ve covered the essentials of the SwiftUI app structure. Remember: Understanding scenes, views, and their relationship is key to creating well-structured, dynamic apps. Keep experimenting, and you’ll be amazed at what you can build. Thanks for joining me for this lesson! Next, you’ll look at View Modifiers,followed by data flow!

See forum comments
Cinema mode Download course materials from Github
Previous: SwiftUI App Structure Next: Conclusion