0% found this document useful (0 votes)
8 views

Lec05 Creating and Combining Views — SwiftUI Tutorials _ Apple Developer Documentation

The document is a tutorial on creating and combining views using SwiftUI to build a Landmarks app for discovering and sharing places. It covers project setup, customizing text views, combining views with stacks, creating custom image views, and integrating MapKit for displaying maps. The tutorial provides step-by-step instructions and emphasizes the use of Xcode's features for real-time feedback and code updates.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lec05 Creating and Combining Views — SwiftUI Tutorials _ Apple Developer Documentation

The document is a tutorial on creating and combining views using SwiftUI to build a Landmarks app for discovering and sharing places. It covers project setup, customizing text views, combining views with stacks, creating custom image views, and integrating MapKit for displaying maps. The tutorial provides step-by-step instructions and emphasizes the use of Xcode's features for real-time feedback and code updates.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Discover Design Develop Distribute Support Account

SwiftUI Tutorials

Creating and Combining Views  Introduction 

SwiftUI Essentials

Creating and Combining


Views
This tutorial guides you through building Landmarks — an app
for discovering and sharing the places you love. Youʼll start by
building the view that shows a landmarkʼs details.

To lay out the views, Landmarks uses stacks to combine and


layer the image and text view components. To add a map to the
view, youʼll include a standard MapKit component. As you refine
the viewʼs design, Xcode provides real-time feedback so you
can see how those changes translate into code.

Download the project files to begin building this project, and


follow the steps below.

40min
Estimated Time Project files  Xcode 12 

Section 1

Create a New Project and


Explore the Canvas
https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 1/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Create a new Xcode project that uses SwiftUI. Explore the


canvas, previews, and the SwiftUI template code.

To preview and interact with views from the canvas in


Xcode, and to use all the latest features described
throughout the tutorials, ensure your Mac is running
macOS Big Sur.

Step 1

Open Xcode and either click “Create a new


Xcode project” in Xcodeʼs startup window, or
choose File > New > Project.

Step 2

In the template selector, select iOS as the


platform, select the App template, and then
click Next.

Step 3

Enter “Landmarks” as the product name,


select “SwiftUI” for the interface and “SwiftUI
App” for the life cycle, and click Next. Choose
a location to save the Landmarks project on
your Mac.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 2/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 4

In the Project navigator, select Landmarks


App.swift.

An app that uses the SwiftUI app life cycle has


a structure that conforms to the App protocol.
The structureʼs body property returns one or
more scenes, which in turn provide content for
display. The @main attribute identifies the
appʼs entry point.

Step 5

In the Project navigator, select ContentView


.swift.

By default, SwiftUI view files declare two


structures. The first structure conforms to the
View protocol and describes the viewʼs
content and layout. The second structure
declares a preview for that view.

Step 6

In the canvas, click Resume to display the


preview.

Tip

If the canvas isnʼt visible, select Editor >


Canvas to show it.

Step 7

Inside the body property, change “Hello,


World!” to a greeting for yourself.

As you change the code in a viewʼs body


property, the preview updates to reflect your
changes.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 3/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Section 2

Customize the Text View


You can customize a viewʼs display by changing your
code, or by using the inspector to discover whatʼs
available and to help you write code.

As you build the Landmarks app, you can use any


combination of editors: the source editor, the canvas, or
the inspectors. Your code stays updated, regardless of
which tool you use.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 4/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Next, youʼll customize the text view using the


inspector.

Step 1

In the preview, Command-click the greeting to


bring up the structured editing popover, and
choose “Show SwiftUI Inspector”.

The popover shows different attributes that


you can customize, depending on the type of
view you inspect.

Step 2

Use the inspector to change the text to “Turtle


Rock”, the name of the first landmark youʼll
show in your app.

Step 3

Change the Font modifier to “Title”.

This applies the system font to the text so that


it responds correctly to the userʼs preferred
font sizes and settings.

To customize a SwiftUI view, you call methods


called modifiers. Modifiers wrap a view to
change its display or other properties. Each
modifier returns a new view, so itʼs common to
chain multiple modifiers, stacked vertically.

Step 4

Edit the code by hand to change the


padding() modifier to the foreground
Color(.green) modifier; this changes the
textʼs color to green.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 5/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation
Your code is always the source of truth for the
view. When you use the inspector to change or
remove a modifier, Xcode updates your code
immediately to match.

Step 5

This time, open the inspector by Command-


clicking on the Text declaration in the code
editor, and then choose “Show SwiftUI
Inspector” from the popover. Click the Color
pop-up menu and choose Inherited to change
the text color to black again.

Step 6

Notice that Xcode updates your code


automatically to reflect the change, removing
the foregroundColor(.green) modifier.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 6/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Section 3

Combine Views Using Stacks


Beyond the title view you created in the previous section,
youʼll add text views to contain details about the landmark,
such as the name of the park and state itʼs in.

When creating a SwiftUI view, you describe its content,


layout, and behavior in the viewʼs body property; however,
the body property only returns a single view. You can
combine and embed multiple views in stacks, which group
views together horizontally, vertically, or back-to-front.

In this section, youʼll use a vertical stack to place the title


above a horizontal stack that contains details about the
park.

You can use Xcodeʼs structured editing


support to embed a view in a container view,
open an inspector, or help with other useful
changes.

Step 1

Command-click the text viewʼs initializer to


show the structured editing popover, and then
choose “Embed in VStack”.

Next, youʼll add a text view to the stack by


dragging a Text view from the library.

Step 2

Open the library by clicking the plus button (+)


at the top-right of the Xcode window, and then
drag a Text view to the place in your code
immediately below the “Turtle Rock” text view.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 7/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 3

Replace the Text viewʼs placeholder text with


“Joshua Tree National Park”.

Customize the location to match the desired


layout.

Step 4

Set the locationʼs font to subheadline.

Step 5

Edit the VStack initializer to align the views by


their leading edges.

By default, stacks center their contents along


their axis and provide context-appropriate
spacing.

Next, youʼll add another text view to the right


of the location, this for the parkʼs state.

Step 6

In the canvas, Command-click “Joshua Tree


National Park”, and choose “Embed in HStack”.

Step 7

Add a new text view after the location, change


the placeholder text to the parkʼs state, and
then set its font to subheadline.

Step 8

To direct the layout to use the full width of the


device, separate the park and the state by

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 8/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation
adding a Spacer to the horizontal stack
holding the two text views.

A spacer expands to make its containing view


use all of the space of its parent view, instead
of having its size defined only by its contents.

Step 9

Finally, use the padding() modifier method


to give the landmarkʼs name and details a little
more space.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 9/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Section 4

Create a Custom Image View


With the name and location views all set, the next step is
to add an image for the landmark.

Instead of adding more code in this file, youʼll create a


custom view that applies a mask, border, and drop shadow
to the image.

Start by adding an image to the projectʼs asset


catalog.

Step 1

Find [email protected] in the project


filesʼ Resources folder; drag it into the asset
catalogʼs editor. Xcode creates a new image
set for the image.

Next, youʼll create a new SwiftUI view for your


custom image view.

Step 2

Choose File > New > File to open the template


selector again. In the User Interface section,
select “SwiftUI View” and click Next. Name the
file CircleImage.swift and click Create.

Youʼre ready to insert the image and modify its


display to match the desired design.

Step 3

Replace the text view with the image of Turtle


Rock by using the Image(_:) initializer,
passing it the name of the image to display.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 10/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 4

Add a call to clipShape(Circle()) to


apply the circular clipping shape to the image.

The Circle type is a shape that you can use


as a mask, or as a view by giving the circle a
stroke or fill.

Step 5

Create another circle with a gray stroke, and


then add it as an overlay to give the image a
border.

Step 6

Next, add a shadow with a 7 point radius.

Step 7

Switch the border color to white.

This completes the image view.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 11/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Section 5

Use SwiftUI Views From Other


Frameworks
Next youʼll create a map that centers on a given
coordinate. You can use the Map view from MapKit to
render the map.

To get started, youʼll create a new custom


view to manage your map.

Step 1

Choose File > New > File, select iOS as the


platform, select the “SwiftUI View” template,
and click Next. Name the new file MapView
.swift and click Create.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 12/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 2

Add an import statement for MapKit.

When you import SwiftUI and certain other


frameworks in the same file, you gain access
to SwiftUI-specific functionality provided by
that framework.

Step 3

Create a private state variable that holds the


region information for the map.

You use the @State attribute to establish a


source of truth for data in your app that you
can modify from more than one view. SwiftUI
manages the underlying storage and
automatically updates views that depend on
the value.

Step 4

Replace the default Text view with a Map view


that takes a binding to the region.

By prefixing a state variable with $, you pass a


binding, which is like a reference to the
underlying value. When the user interacts with
the map, the map updates the region value to
match the part of the map thatʼs currently
visible in the user interface.

When previews are in static mode, they only


fully render native SwiftUI views. For the Map
view, youʼll need to switch to a live preview to
see it render.

Step 5

Click Live Preview to switch the preview to live


mode. You might need to click Try Again or
Resume above your preview.

In a moment, youʼll see a map centered on


Turtle Rock. You can manipulate the map in
live preview to zoom out a bit and see the
surrounding area.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 13/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Section 6

Compose the Detail View


Y h ll f th t d th
https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 14/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation
You now have all of the components you need — the name
and place, a circular image, and a map for the location.

With the tools youʼve used so far, combine your custom


views to create the final design for the landmark detail
view.

ContentView.swiftPreview

1 import SwiftUI
2
3 struct ContentView: View {
4 var body: some View {
5 VStack(alignment: .leading) {
Step 1 6 Text("Turtle Rock")
7 .font(.title)
In the Project navigator, select the Content
View.swift file. 8
9 HStack {
10 Text("Joshua Tree National Park")
11 .font(.subheadline)
12 Spacer()
13 Text("California")
14 .font(.subheadline)

Step 2 15 }
16 }
Embed the VStack that holds the three text
17 .padding()
views in another VStack.
18 }
19 }
20
21 struct ContentView_Previews: PreviewProvider {
22 static var previews: some View {
23 ContentView()

Step 3 24 }
25 }
Add your custom MapView to the top of the
stack. Set the size of the MapView with
frame(width:height:).

When you specify only the height parameter,


the view automatically sizes to the width of its
content. In this case, MapView expands to fill
the available space.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 15/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 4

Click Live Preview to see the rendered map in


the composed view.

You can continue editing the view while


showing a Live Preview.

Step 5

Add the CircleImage view to the stack.

Step 6

To layer the image view on top of the map


view, give the image an offset of -130 points
vertically, and padding of -130 points from the
bottom of the view.

These adjustments make room for the text by


moving the image upwards.

Step 7

Add a spacer at the bottom of the outer


VStack to push the content to the top of the
screen.

Step 8

To allow the map content to extend to the top


edge of the screen, add the ignoresSafe
Area(edges: .top) modifier to the map
view.

Step 9

Add a divider and some additional descriptive


text for the landmark.

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 16/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Step 10

Finally, move the subheadline font modifier


from each Text view to the HStack
containing them, and apply the secondary
color to the subheadline text.

When you apply a modifier to a layout view like


a stack, SwiftUI applies the modifier to all the
elements contained in the group.

Check Your Understanding

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 17/18
2/1/2021 Creating and Combining Views — SwiftUI Tutorials | Apple Developer Documentation

Question 1 of 4

When creating a custom SwiftUI view, where do you declare the viewʼs layout?

In the viewʼs initializer.

In the body property.

In the layoutSubviews() method.

Submit Next Question

Next

Building Lists and


Navigation
With the basic landmark detail view set up, you need
to provide a way for users to see the full list of
landmarks, and to view the details about each
location.

Get started

https://developer.apple.com/tutorials/swiftui/creating-and-combining-views 18/18

You might also like