SwiftUI Projects

4.8 (4 reviews total)
By Craig Clayton
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Chapter 1: SwiftUI Basics

About this book

Released by Apple during WWDC 2019, SwiftUI provides an innovative and exceptionally simple way to build user interfaces for all Apple platforms with the power of Swift.

This practical guide involves six real-world projects built from scratch, with two projects each for iPhone, iPad, and watchOS, built using Swift programming and Xcode. Starting with the basics of SwiftUI, you’ll gradually delve into building these projects. You’ll learn the fundamental concepts of SwiftUI by working with views, layouts, and dynamic types. This SwiftUI book will also help you get hands-on with declarative programming for building apps that can run on multiple platforms. Throughout the book, you’ll work on a chart app (watchOS), NBA draft app (watchOS), financial app (iPhone), Tesla form app (iPhone), sports news app (iPad), and shoe point-of-sale system (iPad), which will enable you to understand the core elements of a SwiftUI project.

By the end of the book, you’ll have built fully functional projects for multiple platforms and gained the knowledge required to become a professional SwiftUI developer.

Publication date:
December 2020
Publisher
Packt
Pages
410
ISBN
9781839214660

 

Chapter 1: SwiftUI Basics

When Apple announced SwiftUI at WWDC in June, I was fortunate enough to be there. As soon as Apple presented SwiftUI, I was like a kid in a candy store because one of my biggest passions in iOS is working on the visual side. I love being able to take a design and try to come as close as I can to matching every detail of a designer's composition. The biggest downfall of using storyboards, which I am still a fan of, is that you cannot quickly prototype. I have ways of doing it, but it takes time, and sometimes you want to go in and try something and not spend a lot of time setting things up like Collection views or Table views with data. SwiftUI helps me focus on creating a beautiful design without needing any data, and when I am ready, I can plug in data. I find this to be the best process because I can add the data layer after completing the design.

I enjoyed designing all six apps that we will cover in this book. I tried to cover a wide range of topics with these six apps. We will build two watch apps, two iPhone apps, and two iPad apps. Most of these features are available on any device; I decided to mix up the apps so that there was a little variety. One thing about this book that might be slightly different is that I have set up the book so we cover design first. After that, we'll focus on the data side. If you do not care about design, you can easily skip this part. Do what you feel is best for you.

In this chapter, we will be working with the following:

  • Views and controls
  • Shapes
  • View layout and presentation

Views and controls are a crucial part of SwiftUI. Some of them you'll be familiar with if you have done iOS development before. Shapes in SwiftUI are super easy to create and use, and once you are comfortable with them, we'll add animations to them to bring them to life. We'll look at Rounded Rectangles, Rectangles, Circles, and even creating Activity Rings later in the book. Finally, view layout and presentation is a big part of SwiftUI, and we'll cover a ton of ways to make beautiful designs and recreate them in SwiftUI.

In this chapter's sample files, you will find a project called SwiftUIBasics. You can follow along with all of the code examples in that file. Since we will be doing a ton of writing, I designed this chapter for you to follow along with me.

In the SwiftUIBasics project, you will see three folders: Views and Controls, Shapes and View Layout, and Presentation. Each folder has all of the completed code, so you can just follow along. Feel free at this time to play around with modifiers. If you are new to programming, just type a . at the end of the line, and you will see a list of other modifiers you can add on.

If you want to type out each example, please feel free to follow along by creating a new project and just create a new SwiftUI file for each step.

You will notice ContentView in this app, but you can ignore it as we will not be using this file in this chapter. ContentView is the default view that you see when you create a new project. We are not going to cover all views and controls in this chapter, but we will cover most of them at some point in this book.

 

Technical requirements

 

Views and controls

Views and controls make up the things you add to your layouts and presentations. In the book, we focus on just learning what you can do and some of the things you cannot do with SwiftUI, instead of comparing them to UIKit.

Text

Text is a view that displays one or more lines of read-only text:

struct ViewsAndControlsTextI: View {
    var body: some View {
        Text('This is Text')
    }
}

Try tapping the Resume button on the right:

Figure 1.1

Figure 1.1

After doing so, you should see the following:

Figure 1.2

Figure 1.2

Text views display using the default font, font size, and the default color of black. In SwiftUI, we can style our views by adding modifiers. Open ViewsAndControlsTextII to see how we can add modifiers:

struct ViewsAndControlsTextII: View {
    var body: some View {
        Text('This is Text')
            .fontWeight(.bold)
            .font(.system(size: 24))
            .foregroundColor(.red)
    }
}

If you tap the Resume button on the left, you will see the following:

Figure 1.3

Figure 1.3

After adding modifiers to the Text view, the text is now red and bold with a font size of 24. Modifiers are used to modify and style a view. Text views are used for read-only text; if you want to add a text field that can accept the user's input, you will use TextField. Let's take a look at this next.

TextField

In this example, we look at TextField. TextField is a control that displays an editable text view. Open ViewsAndControlsTextFieldI. You will notice we are using @State in this example. Since @State is a bigger topic, please ignore it for now; we will cover this topic in detail later in the book:

struct ViewsAndControlsTextFieldI: View {
    @State private var username = ''
    var body: some View {
        TextField('Username', text: $username)
    }
}

If you tap the Resume button on the left, you will see the following:

Figure 1.4

Figure 1.4

The TextField we created in this example uses the default look. Let's move to the next example to see how we can modify the TextField with a border. Open ViewsAndControlsTextFieldII and again ignore @State:

struct ViewsAndControlsTextFieldII: View {
    @State private var username = ''
    var body: some View {
        TextField('Username', text: $username)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

If you tap the Resume button on the left, you will see the following:

Figure 1.5

Figure 1.5

By using the .textFieldStyle modifier, we can give the TextField a rounded border. TextField views are useful for getting user information such as their username for logging into your app. For a more secure field, such as entering a password, you would use SecureField. Let's take a moment to examine SecureField.

SecureField

SecureField and TextField are the same things except that the first one is better for handling sensitive data" if they're both good but the first one is better. The styling is the same for both as well. Open ViewsAndControlsSecure and ignore @State:

struct ViewsAndControlsSecureField: View {
    @State private var password = ''
    var body: some View {
        SecureField('Password', text: $password)
            .textFieldStyle(RoundedBorderTextFieldStyle())
    }
}

If you tap the Resume button on the left, you will see the following:

Figure 1.6

Figure 1.6

Visually, TextField and SecureField look the same, but as soon as you start to type inside SecureField, you immediately see a difference. Now, let's take some time to look at how we can display images in SwiftUI.

Image

We move to our next SwiftUI view, Image. Let's look at how we can display local images in SwiftUI:

struct ViewsAndControlsImage: View {
    var body: some View {
        Image('lebron-james-full')
    }
}

If you tap the Resume button on the left, you will see the following:

Figure 1.7a

Figure 1.7a

We just looked at how you can display local images in either the Assets Catalog or the project folder. If you need to download the image from a URL, this process takes a bit more code. We do not cover downloading photos from URLs as that is out of scope for this book, mostly because I do not have a place to store them. There are plenty of online resources that cover this topic in detail.

Let's look at how we can modify the size of images.

Modifying an image

In SwiftUI, when you need to resize an image, you have to use the .resizeable modifier. Let's look at how this works in SwiftUI. Open ViewsAndControlsResizableImage:

struct ViewsAndControlsResizableImage: View {
    var body: some View {
        Image('lebron-james-full')
            .resizable()
            .frame(width: 124, height: 92)
    }
}

Tap the Resume button; you'll see the following:

Figure 1.7b

Figure 1.7b

In this example, we use the .resizable and .frame modifiers to adjust the size of the image. If you are working with images that come from a URL, you will have a different setup. You still have to use the .resizable and the .frame modifier even if the image comes from a URL. Let's turn our attention to SF Symbols.

In iOS 13, Apple introduced SF Symbols, and with the release of iOS 14, we got even more. These symbols work with accessibility requirements and grow in size when the user changes their system font size. In the following code, we are displaying a rain cloud:

struct ViewsAndControlsSFSymbol: View {
    var body: some View {
        Image(systemName: 'cloud.heavyrain.fill')
    }
}

Tap the Resume button; you'll see the following:

Figure 1.8

Figure 1.8

If you would like to see the entire library of SFSymbols v1 and v2, you can download the app from https://developer.apple.com/sf-symbols/. A screenshot of the app looks as follows:

Figure 1.9

Figure 1.9

With SF Symbols, you have access to over 2,400 configurable symbols that you can use in your Apple apps. We use SF Symbols throughout the book, and you should become familiar with them. Moving to the next example, let's look at how to create buttons.

Buttons

A basic SwiftUI button provides an action and a label. We can use closure blocks or execute a method inside of this action. Let's look at a default SwiftUI button by opening up ViewsAndControlsButtonI:

struct ViewsAndControlsButtonI: View {
    var body: some View {
        Button(action: { print('Button tapped') }) {
            Text('Button Label')
        }
    }
}

If you tap the Resume button on the left, you'll see the following:

Figure 1.10

Figure 1.10

SwiftUI default buttons use a default label that has no style attached. You can add any type of view inside of the label. You can also use modifiers to give a button a certain look and feel.

Let's move to the next example. Open ViewsAndControlsButtonII and let's see how we can style a button:

struct ViewsAndControlsButtonII: View {
    var body: some View {
        Button(action: { print('Button tapped') }) {
            Text('Button Label')
        }
        .padding(10)
        .background(Color.red)
        .foregroundColor(.white)
    }
}

If you tap the Resume button on the left, you'll see the following:

Figure 1.11

Figure 1.11

Our button now has a red background with white text and a padding of 10 pixels around the text. You can turn a default button into any design you may need. We'll learn how to create custom buttons and custom button styles that we can share with other buttons in this book. For now, let's move to the next set of examples, shapes.

 

Shapes

In SwiftUI, we have five preset shapes that you can work with, and they are super easy to create. The Circle, Rectangle, Ellipse, and Capsule are all created the same way. Let's look at each one and stop when you get to Rounded Rectangle.

Circle

Open ShapesCircle and let's take a look at how we can create a circle:

struct ShapesCircle: View {
    var body: some View {
        Circle()
            .fill(Color.red)
            .frame(width: 50, height: 50)
    }
}

If you tap the Resume button on the left, you'll see the following:

Figure 1.12

Figure 1.12

Creating shapes is easy in SwiftUI; in the preceding example, our circle is filled with red and is 50x50 in size. We will use custom shapes to create our UI. We can now move on to Rectangle.

Rectangle

We are now going to take a look at the Rectangle. Open ShapesRectangle and in our next example, let's take a look at creating a basic rectangle:

struct ShapesRectangle: View {
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 50)
    }
}

Tap on the Resume button, and you'll see the following:

Figure 1.13

Figure 1.13

In this last example, our Rectangle is filled with red and is 50 x 50 in size. Let's move on to our next example.

Ellipse

We'll now take a look at an ellipse. Open ShapesEllipse, and you will see we applied the same red fill with a size of 100 x 50:

struct ShapesEllipse: View {
    var body: some View {
        Ellipse()
            .fill(Color.red)
            .frame(width: 100, height: 50)
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.14

Figure 1.14

We created an Ellipse, and as you can see, the code is not changing – the shape making, for the most part, has the same pattern. Let's move to the Capsule next.

Capsule

We are onto the next to last shape, the Capsule. Capsules are handy for creating bar charts, which we do later in this book. Let's take a minute and look at a basic Capsule. Open up ShapesCapsule:

struct ShapesCapsule: View {
    var body: some View {
        Capsule()
            .fill(Color.red)
            .frame(width: 200, height: 50)
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.15

Figure 1.15

We now have a capsule sitting in the center of the screen. We can now move on to the final shape, and that's the Rounded Rectangle.

Rounded Rectangle

The Rounded Rectangle is the only shape that has a parameter, .cornerRadius, when you create one. Let's open ShapesRoundedRectangle and check out our final shape:

struct ShapesRoundedRectangle: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 25)
            .fill(Color.red)
            .frame(width: 200, height: 25)
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.16

Figure 1.16

We are finished looking at shapes, but remember that all shapes by default have a fill color of black. Next, we'll focus on the view layout and presentation.

 

View layout and presentation

Let's get into this next section, but keep in mind that you can embed these views inside of other views. We won't cover that in this chapter as it is something we do a ton throughout this book. Let's move to VStack.

VStack

When you use a VStack, it arranges all of its children in a vertical line. Let's take a look at this in operation by opening ViewLayoutVStack:

struct ViewLayoutVStack: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.17

Figure 1.17

In this example, we are displaying two Rectangles on a vertical line in the center of the stack. To make our Rectangle fill all available vertical space, we would need to use a spacer. Let's see what happens when we add a spacer.

VStack with a spacer

Using a spacer allows us to manipulate how our objects respond inside of the VStack. In this specific example, we are adding a spacer in between each rectangle. Open ViewLayoutVStackSpacer:

struct ViewLayoutVStackSpacer: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
            Spacer()
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.18

Figure 1.18

Putting our spacer in between each rectangle pushes our rectangles to the top and bottom, respectively. If you move the spacer below the two Rectangles, this moves both Rectangles to the top of the screen. You would get the opposite if you moved the spacer above both Rectangles.

Take a minute to move the spacer around inside of the VStack, to see how it behaves. When finished, let's move to the HStack.

HStack

Our next container is called an HStack, and you probably guessed it – the HStack displays its children on a horizontal line:

struct ViewLayoutHStack: View {
    var body: some View {
        HStack {
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.19

Figure 1.19

We pretty much have the same code as we did for the VStack example, except using an HStack as the main container. HStack, by default, is aligned in the center of the screen. Now, just as we did with VStack and a spacer, we can do the same by manipulating the Rectangles here to get the layout we need.

HStack with spacer

To illustrate a spacer in an HStack, we use two spacers, instead of one, along with three rectangles. Open ViewLayoutHStackSpacer, and let's see it in action:

struct ViewLayoutHStackSpacer: View {
    var body: some View {
        HStack {
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
            Spacer()
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
            
            Spacer()
            Rectangle()
                .fill(Color.red)
                .frame(width: 50, height: 50)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.20

Figure 1.20

By adding two spacers, we get rectangles on the right, on the left, and directly in the middle. Take some time and move the spacers around, so you get a feel for how it works as we use it throughout the book. Finally, in our last stack example, we'll take a look at the ZStack.

ZStack

ZStack is a bit different than VStack and HStack because instead of its children aligning along a particular axis when they are added to the container, with ZStack they are stacked on top of each other. Open ViewLayoutZStack to see this in action:

struct ViewLayoutZStack: View {
    var body: some View {
        ZStack {
            Color.black
            Text('Craig Clayton')
                .foregroundColor(.white)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.21

Figure 1.21

In this ZStack example, we add the color black to our ZStack along with a Text view. You might be asking how we can add a color to our view. Well, colors are nothing more than views, which means they can be added just like other views. Right now, you might be thinking that ZStack is nothing special, but it is, as you will see soon. Let's look at another example by opening ViewLayoutZStack:

struct ViewLayoutZStack: View {
    var body: some View {
        ZStack {
            Color.black
                .edgesIgnoringSafeArea(.all)
            Text('Craig Clayton')
                .foregroundColor(.white)
            Text('Craig Clayton')
                .foregroundColor(.white)
				.offset(x: 0, y: 100)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.22

Figure 1.22

In the preceding example, we set the background color to black. Then we extend the color to the edges and ignore the safe areas on all edges of the device. Next, we have two Text views, but one of them has an offset. If you remove the offset, the Text views get stacked on top of each other, just as you would expect when adding views to a ZStack. Using the offset, we can move our views around on a ZStack. Let's look at one more ZStack example; this time, we will use an alignment with a ZStack.

Maybe this example will show you the reason for my excitement over using ZStack. Open ViewLayoutZStackAlignment:

struct ViewLayoutZStackAlignment: View {
    var body: some View {
        ZStack(alignment:Alignment(horizontal: .trailing,                  vertical: .top)) {
            Color.black
                .edgesIgnoringSafeArea(.all)
            Text('Another Example')
                .foregroundColor(.white)
                .offset(y: 25)
            
            Text('Craig Clayton')
                .foregroundColor(.white)
                .offset(y: 50)
            
            Rectangle()
                .fill(Color.red)
                .frame(width: 100, height: 25)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.23

Figure 1.23

HStacks have vertical alignments, and VStacks have horizontal alignments. ZStacks can utilize both horizontal and vertical alignments. A ZStack with an alignment helps get the views in the general direction required, and we can then fine-tune the placement using x and y offsets. As we work through more and more designs in this book, this will make more sense to you.

ZStack is one of my favorite features in SwiftUI, and I use it a ton in this book; the more you get familiar with it, the more you'll understand why.

Take some time messing with ZStack, and when you are ready, move on to the next example.

Group

A Group in SwiftUI is a container that you can use to group view elements without any special alignment. Open ViewLayoutGroup, and let's take a look at how Group works:

struct ViewLayoutGroup: View {
    var body: some View {
        VStack {
            Group {
                Text('Gabriel Lang')
                Text('John Brunelle')
                Text('Matthew Arieta')
                Text('Ralph Dugue')
            }
            .foregroundColor(.red)
            .font(.largeTitle)
			Group {
                Text('Alex Burnett')
                Text('Craig Heneveld')
                Text('Bill Munsell')
                Text('Wayne Ohmer')
            }
            .foregroundColor(.red)
            .font(.largeTitle)
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.24

Figure 1.24

In this example, we have text views that are inside of a VStack, and instead of adding foregroundColor to each text, I added it to the Group. Also note that you can use this technique with VStack, HStack, and ZStack. Grouping is also great for applying animations to the entire Group or if you want to manipulate the Group differently based on the device in use. Let's move to the next example.

ForEach

A ForEach struct is a bit different than the forEach() you might be accustomed to. SwiftUI's ForEach is a view struct, which allows us to add it directly to the body. We can create views using the ForEach struct because it takes an array of unique items. Open ViewLayoutForEach, and let's take a few moments to see how ForEach works:

struct ViewLayoutForEach: View {
    let coworkers = ['Gabriel Lang', 'John Brunelle', 'Matthew   
        Arieta', 'Wayne Ohmer', 'Ralph Dugue', 'Alex 
         Burnett', 'Craig Heneveld', 'Bill Munsell']
    var body: some View {
        VStack {
            ForEach(coworkers, id: \.self) { name in
                Text(name.uppercased())
            }
        }
        .foregroundColor(.blue)
        .font(.headline)
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.25

Figure 1.25

In this example, we use a ForEach struct to loop through the array of coworkers. Each time it loops through, it grabs the id (which needs to be unique; we are using each name as our unique identifier). During the loop, it also sets the name to uppercase, sets the text foreground color to blue, and finally sets the font to headline. We can use ForEach as a way to work with an array of data. Let's now take the time to look at List.

List

A List is a container that displays a row of data in a single column. Open ViewLayoutList and let's see a List in action:

struct ViewLayoutList: View {
    var body: some View {
        List {
            Text('1')
            Text('2')
            Text('3')
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.26

Figure 1.26

Here, we are displaying a list of text views that are embedded into a List. Now, let's take a minute and understand the difference between ForEach and List.

Differences between ForEach and List

When you are working with a List, you can display mixed content as well as scroll. List also utilizes the reusing cell pattern, which is super-efficient. Now, as far as design goes, it is much harder to customize List view defaults. When you use a ForEach struct, it works only with a collection.

ScrollView

A ScrollView allows you to scroll content either horizontally or vertically. Open ViewLayoutScrollHorizontal to move to the next example:

struct ViewLayoutScrollHorizontal: View {
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 15) {
                ForEach(0..<10) { _ in
                    Rectangle()
                        .fill(Color.red)
                        .frame(width: 50, height: 50)
                }
            }
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.27

Figure 1.27

For this example, we have a ScrollView wrapped around an HStack, which means its contents will scroll horizontally. In our ForEach, we are creating 10 Rectangles, which are red and 50 x 50. Open ViewLayoutScrollVertical, and let's see how we can do this vertically:

struct ViewLayoutScrollVertical: View {
    var body: some View {
        ScrollView {
            VStack(spacing: 15) {
                ForEach(0..<20) { _ in
                    Rectangle()
                        .frame(width: 50, height: 50)
                }
            }
        }
    }
}

Tap the Resume button, and you'll see the following:

Figure 1.28

Figure 1.28

In this final example, we changed the HStack to a VStack from our last example. SwiftUI makes it easy to create a specific UI design. We have looked at views and controls, shapes, and view layouts. We now understand that we can use modifiers to update how they look visually and where they will be laid out on the screen. By the end of this book, you will have learned how to break down designs specifically for SwiftUI apps.

 

Summary

In this chapter, we looked at the basics of SwiftUI, focusing on views and controls, shapes, and finally, view layout. We learned about how to add styles to our views and controls. This chapter served as a useful introduction; as we progress through the book, we will look at even more SwiftUI views and controllers.

In the next chapter, we will go a step further and build a watch app using SwiftUI. We will not be focused on the design of a specific app, but we will be focused on making sure we get better at understanding the basics. We covered a lot in this chapter, but we will see each of these views repeatedly throughout the book.

About the Author

  • Craig Clayton

    Craig Clayton is a self-taught, senior iOS engineer at Adept Mobile, specializing in building mobile experiences for NBA and NFL teams. He also volunteered as the organizer of the Suncoast iOS meetup group in the Tampa/St. Petersburg area for 3 years, preparing presentations and hands-on talks for this group and other groups in the community. He has also launched Cocoa Academy online, which specializes in bringing a diverse list of iOS courses, ranging from building apps to games for all programming levels, to the market.

    Browse publications by this author

Latest Reviews

(4 reviews total)
If you need to understand key features of iOS and SwiftUI come together, this is a good reference.
Good quality books and good value
muy buen libro espero aprender mucho de el gracias pro todo

Recommended For You

SwiftUI Projects
Unlock this book and the full library for FREE
Start free trial