Unit 18: Adaptive User Interfaces Flashcards

1
Q

Asset catalog

A

the best place to store the images for the app; located in .xcassets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Auto Layout

A

used to build adaptive interfaces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Constraint

A

a rule in Auto Layout that defines how views should be laid out or sized

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Stack view

A

a rule in Auto Layout that defines how views should be laid out or sized

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

18.1 - SimpleCentre

A

You’ll start by building an app to experiment with adaptive user interfaces and learn the basics of Auto Layout.
In Xcode, create a new project.
Use the iOS template for a Single View Application.
Name the product “SimpleCenter.”
Save the project to the desktop.
Select Main.storyboard in the project navigator.
At the bottom of the window you’ll see a button bar:​

It indicates you’re currently viewing the canvas at the size of an iPhone 6s.
Use the View as: button to display a set of options for the device size and orientation you to see on the canvas.

Click the button and choose the smallest device (iPhone 4s).

`

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Not Adapting

A

First, you’ll experiment with a layout that doesn’t adapt.
Open the library pane and search for “label.”
Drag a label to the center of the canvas. You’ll see blue dotted lines when you’ve successfully centered the label horizontally and vertically.
Double-click the label and edit its contents to “Hello!”
Notice that the label “Hello!” is still centered top to bottom and left to right.
Now experiment by clicking different device sizes at the bottom of the screen. Does the “Hello!” label stay centered on the screen as you change screen sizes?
Try changing the orientation from portrait (tall) to landscape (wide) mode. Does the “Hello!” label stay centered on the screen in landscape mode?
Finally, go back to the smallest iPhone device size and to portrait mode. ​
On this screen, the “Hello!” label once again appears in the center vertically and horizontally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What’s going on?

A

The size and location of every view in Interface Builder is defined ​
as a rectangle, known as its frame. This is similar to plotting points ​
on a coordinate system, which you might remember from math class.
When you add a view, like the “Hello!” label, to the canvas, the view’s location is a certain distance from the top and a certain distance from the left. Those distances remain the same for every screen size and orientation. So the label will appear centered for one layout but will be way off-center for the others.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Making Views Adapt with Auto Layout

A

A favorite tool that iOS developers use for building adaptive user interfaces is Auto Layout. In your earlier experiment, you saw that the position of the text label stayed the same regardless of screen size or orientation. With ​
Auto Layout, you set up rules, called constraints, that define how views will be laid out.
Note: As you first learn about Auto Layout, you might find it’s easier to think of the word “rule” whenever you see the word “constraint.”
Auto Layout is very powerful and can be used to create complex layouts. There are many variations
“in how you set up constraints.
In this lesson, you’ll focus on using just a few common constraints that will help you achieve consistent results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Adding constraints

A

Check out the bottom of the Interface Builder editor. You’ll see four buttons that will help you build adaptive user interfaces.

The second button from the left , the one that looks like a bar chart, ​
is the Align button.

A popover appears with various alignment constraints. Some of the constraints aren’t enabled; you’ll only see those when you select more ​
than one view.
The constraints you want to set right now are Horizontally in Container ​
and Vertically in Container:
Select those two checkboxes.
Make sure the numbers to the right are set to 0.
Click the Add 2 Constraints button.
Note: Make sure that you check the checkboxes and click the Add 2 Constraints button.
When you run your app, the constraints you added will make sure the view ​
is centered vertically and horizontally on all screens and orientations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Fixing Issues

A

Once you’ve added the constraints, you should see two blue lines, ​
one vertical and one horizontal. These lines are the constraints that ​
you just added.
If you don’t see any lines, you may have missed a step in the last section. ​
For example, it’s easy to forget to click the Add 2 Constraints button after checking the checkboxes. Go back and try again.
If you see orange lines, don’t panic. This next section will help you resolve the issue.
When you’re working in Interface Builder, sometimes the constraints you’ve set up don’t agree with the current frame of a view.
To demonstrate this, drag the “Hello!” label down and a little bit to the left. You might need to click somewhere else on the canvas before selecting ​
the label; otherwise you could end up selecting a constraint (one of the ​
blue lines) instead of the label.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Fixing Issues [cont’d]

A

Leave the label selected after you move it. The canvas should look something like the image to the left.
Now your lines have turned orange, indicating that the current frame ​
of the label doesn’t agree with the constraints you set. The outlined orange rectangle shows you where the constraints say the label should go, and the numbers on the orange vertical and horizontal lines indicate how far the label needs to move.
Whenever the frame of a view on the canvas is different from where the constraints will put the view when you run the app, you’ll have a problem. You can fix it in one of two ways:
Update the frame to match the constraints.
Update the constraints to match the frame.
In fact, Interface Builder can fix the issue for you. To make it happen, start ​
by locating the Resolve Auto Layout Issues button, the right-most button ​
in the Auto Layout button group .

Clicking the button brings up a menu of choices.
In this case, you want the label to be centered, so you’ll update the frame
of the label view.
Select the label, if it isn’t already.
Click the Resolve Auto Layout Issues button.
Select Update Frames from Selected Views.
Notice that the label moved back to the center of the canvas and the lines turned blue again. The frame of the label agrees with the constraints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Testing

A

Now that you’ve added constraints to keep the label centered horizontally and vertically, test that it works on other screens.
Like you did before, choose different devices to change the size of the canvas. Also change the orientation from portrait to landscape.
The label view should stay centered for every screen size and orientation. The layout is automatically adapting based on the constraints you’ve applied.
Congratulations! You’ve built an adaptive user interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

18.2 ElementQuiz

A

In the previous part of this lesson, you created a simple app to learn how ​
to center a view horizontally and vertically on different screens. In this part, you’ll build an app to quiz users on the elements of the periodic table. The app will work a bit like flash cards. The user sees the element symbol and atomic weight, then taps a button to reveal the name of the element.
You’ve already learned that constraints in Auto Layout provide a powerful way to build an adaptive user interface. But there’s a degree of complexity in that power. In many apps, the main user interface is similar to a stack or list of views, and the stack works either from top to bottom or from left to right. You can use constraints in Auto Layout to define these kinds of interfaces, but iOS provides a more convenient approach. It’s called a stack view.
In your quiz app, you’ll use a UIStackView to arrange the views from top to bottom. You’ll then use constraints to center the stack view on the canvas. Along the way, you’ll also use constraints for the width and height of an image view…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

ElementQuiz [cont’d]

A

Select Main.storyboard in the project navigator.
Click the View as: button and select the smallest device (iPhone 4s).

The user interface of this app consists of four views, from top to bottom:
An image view to display an image of the chemical element
A label to display either a question mark or the name of the element
A button to show the answer
A button to go to the next element
Drag these items from the library onto the canvas. Remember that you can use the filter bar at the bottom of the library to narrow your search. Arrange the views from top to bottom.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Image View Size

A

When you use Auto Layout with an image view, the view, by default, will adjust its size to fit the size of the image. But you often want to make sure the image view stays a fixed size. That’s the case with the ElementQuiz app.
Change the size of the image view:
Select the image view.
In the Size inspector, set the width to 140 and the height to 140.
Note that changing the size in the Size inspector doesn’t set constraints; it only adjusts the size in Interface Builder. Similar to what you did in the first part of this lesson, you need to set constraints to have views adapt using Auto Layout and stack views.
To set width and height constraints on the image view:
Select the image view.
Click the Pin button at the bottom of the Interface Builder editor.
A popover appears with various constraints. Use each constraint to set, ​
or pin, some aspect of the layout of the view to a desired value.

The constraints you’re interested in are Width and Height. To set those constraints:
Select those two checkboxes.
Make sure the numbers to the right are set to 140.
Click the Add 2 Constraints button.
Remember: It can be easy to forget to click the Add 2 Constraints button.
The canvas should look like the image to the left, with red lines around the ​
image view. The red lines mean you haven’t defined enough constraints for Auto Layout to figure out the position and the size of the image view. In this case, you’ve defined the size, but you haven’t defined the position of the view. You’ll do that a little later in this lesson.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Configuring Label and Buttons

A

Before arranging all these views in a stack view, you’ll need to configure ​
the label and the buttons.
Configure the label:
Select the label.
In the Attributes inspector, click the Font button to display the Font ​
popup menu.
Change the Style to Bold and the Size to 24, then click Done (see left).
Change the string in the label to “Answer Label.”
Don’t worry if the label isn’t centered or if the text is a bit cut off. You’ll fix those problems in the next section.
Even though the contents of this label will be changed at runtime, setting ​
a string value besides “Label“ makes the purpose of the label clear.
Configure the buttons:
Set the title of the button below the label to “Show Answer.”
Set the title of the bottom button to “Next Element.”
For now, the text of the buttons may be truncated. You’ll also address that issue in the next section.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Adding a Stack View

A

At the moment, the views you’ve added aren’t very tidy. That’s fine, as long as they’re arranged top to bottom. In this section, you’re going to put all of those views into an instance of UIStackView. Stack views keep views arranged either vertically or horizontally.
To put all four views in a stack view:
Select the four views. You can Shift-click to select multiple items or drag over all four items on the canvas. When you’re finished, the canvas should look similar to this, with white selection handles visible at the edges of the selected views.
With the views selected, click the Stack button at the bottom of the Interface Builder editor .
The canvas should look similar to this (see left).
Note that the views in the stack will appear either centered, left-aligned, ​
or right-aligned, depending on how the views were arranged before you clicked the Stack button.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Centering the Stack View

A

To define the position of the stack view, you’ll add two constraints. You’ll use the technique you learned in the last part of the lesson to center the stack view vertically and horizontally. Since your four views are now contained in the stack view, they’ll all be centered as well.
It can be tricky to select a stack view. Choose one of these techniques:
Drag over the stack view from outside the stack view.
Select Stack View from the outline view (see image left).
Notice the hierarchy in the outline view. You can see that the stack view contains the image view, the label, and the two buttons.
To add constraints to the stack view, go through the same steps you used ​
to center the text label in Part 1 of this lesson:
Select the stack view using one of the techniques above.
Click the Align button at the bottom of the Interface Builder editor.
Add constraints for Horizontally in Container and Vertically in Container (see image left).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

More Orange Lines

A

After you add these constraints, you’ll probably see orange lines on the canvas. You just set constraints to center the stack view vertically and horizontally, but you can see that the stack view still isn’t centered. As ​
you learned in Part 1, the orange lines indicate that the frame of the view ​
doesn’t agree with the constraints. That’s clearly what’s happening here.
You’ll fix the issue the same way you did in Part 1:
Make sure the stack view is selected.
Click the Resolve Auto Layout Issues button at the bottom of the Interface Builder editor .
Choose Update Frames from Selected Views.
Note: If the Update Frames menu item is not enabled, click inside the canvas to deselect the stack view, then select it again.
The stack view should now be centered on the canvas, and blue lines showing the constraints to center horizontally and vertically should ​
be visible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Configuring the Stack View

A

The last step in building the user interface is to configure the stack view. ​
You can change various properties of a stack view to get the result you want.
In this case, all the views should be centered horizontally within the stack view. But the views also need some vertical room between them, so you’ll need to increase the spacing a bit.
The two stack view settings you’ll use are:
Alignment: How the views are arranged within the stack.
Spacing: How much space is between each view in the stack.
To configure the stack view:
Select the stack view.
In the Attributes inspector set Alignment to Center and Spacing to 12.
The views should now appear centered horizontally in the stack view with ​
a nice amount of vertical space between them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Testing

A

Like you did in the last part of this lesson, choose different devices to change the size of the canvas. While you’re at it, change the orientation from portrait to landscape.
The constraints keep the stack view centered. And the stack view keeps ​
the views within it centered and with the correct spacing between them.

22
Q

Adding Images

A

If you build and run the ElementQuiz app, you’ll notice that no images appear. That’s because you need to add images to your project and set ​
the image of the image view. You’ll add the images in this section.
In the Finder, go to the Class Resources folder and locate a folder named Element Images. Add the images in this folder to the asset catalog of your Xcode project:
Select Assets.xcassets from the project navigator (see image left).
Drag the images from the Element Images folder in the Finder to the space below the “AppIcon” entry in the Xcode asset catalog.
The result should look like the image to the left.
In the next few sections, you’ll make these images appear in the user interface of your app.

23
Q

Adding Outlets and Actions

A

You’ve created a user interface that will adapt to different devices and orientations. Now it’s time to use outlets and actions to connect those ​
views to the code.
Note: If you need to refresh your memory on how to create outlets and actions, see the Actions and Outlets lesson for step-by-step instructions.
As the user navigates through different elements in ElementQuiz, you’ll ​
need to update the image view and the answer label.
Create an outlet named imageView for the image view.
Create an outlet named answerLabel for the label view.
When the user taps the Next Element button, you want your code to show the next chemical element. When the user taps the Show Answer button, you want the answer label to change from a question mark to the element name. To make all this work, you need to add an action for each button.
Create an action named gotoNextElement() connected to the Next Element button.
Create an action named showAnswer() connected to the Show ​
Answer button.

24
Q

Adding Code

A

You’ve created an adaptive user interface and connected it to Swift code by creating outlets and actions. Now it’s time to add the code that will give your app its behavior.
Data models
The app will show a list of chemical element symbols one at a time. You’ve seen that a list of items in Swift is an array. The data model for this app is ​
an array of element names.
Add a constant property called elementList to ViewController.swift and initialize it with the following element names:
let elementList = [“Carbon”, “Gold”, “Chlorine”, “Sodium”]
You’ll also need to keep track of which element is currently displayed, so you can access the image and answer that correspond to it. Remember that you access items in an array by index, so your code will keep track of the current array index.
Add a variable property called currentElementIndex to ViewController.swift, and initialize it to zero:
var currentElementIndex = 0

25
Q

Note that elementList is constant…

A

…It won’t change as the app runs. But currentElementIndex is variable. As the user navigates through the elements, your code will update the current index.
Updating the Element
When the app first launches, you’ll display the first element. You’ll also need to update which element is displayed when the user clicks the Next Element button. You can combine the core logic for both of these steps into a single method.
Write an updateElement() method in ViewController.swift that sets the answer label to “?” and creates and sets the correct image.
func updateElement() {​
answerLabel.text = “?”​
let elementName = elementList[currentElementIndex]​
let image = UIImage(named: elementName)​
imageView.image = image​
}
Here’s a breakdown of what’s going on.

The line below sets the text of the answer label to a question mark. The app will display the actual answer when the Show Answer button is tapped:
answerLabel.text = “?”
This line accesses the element name from the list using the currentElementIndex property as the index:
let elementName = elementList[currentElementIndex]
This line creates a new UIImage instance by looking in the asset catalog ​
for an image with a matching name:
let image = UIImage(named: elementName)
This line sets the image of the image view to the newly created image instance:
imageView.image = image
To show the first element in the list when the app launches and the view loads, you’ll add a call to updateElement() to viewDidLoad():
override func viewDidLoad() {​
super.viewDidLoad()​
updateElement()​
}

26
Q

elementList (cont’d)

A

The line below sets the text of the answer label to a question mark. The app will display the actual answer when the Show Answer button is tapped:
answerLabel.text = “?”
This line accesses the element name from the list using the currentElementIndex property as the index:
let elementName = elementList[currentElementIndex]
This line creates a new UIImage instance by looking in the asset catalog ​
for an image with a matching name:
let image = UIImage(named: elementName)
This line sets the image of the image view to the newly created image instance:
imageView.image = image
To show the first element in the list when the app launches and the view loads, you’ll add a call to updateElement() to viewDidLoad():
override func viewDidLoad() {​
super.viewDidLoad()​
updateElement()​
}

27
Q

Checkpoint

A

Build and run the app. The image of the first element should appear, and ​
the answer label should show a question mark. That’s good. But tapping the buttons doesn’t cause any action. It’s time to make that happen.

28
Q

Showing the Answer

A

Earlier you created the action method showAnswer(). To actually show the answer, you’ll access the element name for the element at the current index and set that as the text of the answerLabel.
@IBAction func showAnswer(_ sender: AnyObject) {​
answerLabel.text = elementList[currentElementIndex]​
}

29
Q

Checkpoint

A

Build and run the app. Tapping the Show Answer button should now show the correct element.

30
Q

Navigating Between Elements

A

Last of all, you need to add functionality to navigate to the next element.
Since you access the items in an array by index, you can calculate the value of the next element by adding 1 to the current index. Once the current index is updated, you can call the updateElement() to update the user interface to display the element at the new current index.
@IBAction func gotoNextElement(_ sender: AnyObject) {​
currentElementIndex += 1​
updateElement()​
}

31
Q

Checkpoint

A

Build and run the app. Tapping the Next Element button should show the next element.
What do you think will happen if you tap the Next Element button after you reach the end of the list? Try it and see.

32
Q

A Crash

A

Tapping the Next Element button on the last element in the list had a bad result. It froze the app in the simulator. You’ll see something like this in Xcode:

The ElementQuiz app has crashed.
When your app crashes, there’s no reason to panic. The first thing to do is look at the console, which will sometimes have useful information about what went wrong. In this case, the last line in the console says:
fatal error: Index out of range
The red highlight shows you the line in the code where the error occurred:
let elementName = elementList[currentElementIndex]
According to this information, an index is used that’s outside of the expected range. And since the only index in that line of code is currentElementIndex, it must be the one that’s causing the fatal error.
The crash happened on the line of code where the index is used. But that’s not where you’ll go to fix it. If the index becomes out of range, the problem must be where the value of the index is updated.
In this app, that happens in the gotoNextElement() action method:
@IBAction func gotoNextElement(_ sender: AnyObject) {​
currentElementIndex += 1​
updateElement()​
}

33
Q

Stop and think about the problem…

A

…What are its symptoms? When you tapped the Next Element button, things worked fine until you got to the ​
last element in the list. Do you have an idea what’s causing the problem?
Remember that you can only access an index if that index exists in the array. Otherwise there will be an “Index out of range” error.
The elementList contains four items with indexes 0, 1, 2, and 3. When the last element is shown, the value of currentElementIndex is 3, the last index.
The code currently keeps adding 1 to the index. So when you tap the button again, gotoNextElement() is called, and 1 is added to currentElementIndex. The value is now 4. But since there’s no index 4 in the array, the next time currentElementIndex is used to access the array, the crash occurs.

34
Q

Fixing the Crash

A

For ElementQuiz, you want the app to go back to the beginning of the list when the user gets to the last element and taps the Next Element button.
To implement this behavior without causing a crash, you’ll need to detect when you’ve arrived at the end of the list.

You can use the count property of the elementList array to help make this decision in your code:
@IBAction func gotoNextElement(_ sender: AnyObject) {​
currentElementIndex += 1​
if currentElementIndex >= elementList.count {​
currentElementIndex = 0​
}​
updateElement()​
}

35
Q

Checkpoint

A

Build and run the app. Tapping the Next Element button should show the next element.
Tap at the end of the list to make sure the app cycles successfully back to the beginning.

36
Q

Designing the Model

A

The model for this app is very simple. It’s just an array of strings.
This model works for ElementQuiz because the string value is both the answer that’s displayed and the name of the image that’s displayed.

If you wanted to build a more complex app, you might create a ChemicalElement struct to contain more information:
struct ChemicalElement {​
    let symbol: String​
    let name: String​
    let atomicWeight: Int​
    let imageName: String​
}
37
Q

The data model above…

A

…could support things like quizzing on more than just the element name. It could also allow the name of the image to be different from the name of the element that’s displayed in the user interface.
When building apps, developers often need to make decisions like this. In this case, there’s a trade-off between the simplicity of a single string and the structure and functionality of a custom type.
For the ElementQuiz app, a simple data model of a string was sufficient for everything the app needed to accomplish.

38
Q

18.3 Animal Sounds

A

In the last part of the lesson, you created an app to quiz users on chemical elements. Along the way, you learned how to use a stack view and a few Auto Layout constraints to create an adaptive user interface. In this part, you’ll create an app that plays animal sounds. A child taps an animal picture button, which displays the animal sound in text and makes the appropriate sound.

39
Q

Animal Sounds App

A

The user interface of this app is more complex than you’ve built before. ​
You’ll create a horizontal row of three animal buttons and a vertical column of views, with the row of buttons between two labels.
To create this interface, you’ll take advantage of a powerful feature of stack views: using stack views inside of other stack views. With nested views, you’ll find it’s fast and easy to lay out a user interface.
In this part, you’ll be practicing things you’ve already done, so there will be fewer step-by-step instructions. You can always look back at the previous part or at previous lessons to refresh your memory.

40
Q

Steps

A

In Xcode, create a new project.
Use the iOS template for a Single View Application.
Name the product “AnimalSounds.”
Save the project to the desktop.
Select Main.storyboard in the project navigator.
Click the View as: button and then select the smallest device (iPhone 4s).

You’ll build the user interface in two phases. First, you’ll create the row ​
of buttons. Next, you’ll create the rest of the interface and incorporate​
the row into it.

41
Q

Create a Row of Buttons

A

Each button uses an emoji at a large font size as its title.
Drag a button onto the canvas.
Set the button title to the cat emoji . Use Command-Control-Space to bring up the emoji picker.
In the Attributes inspector, change the font size to 72.
Refer back to the previous part of this lesson if you need to refresh your memory on how to change the button title or font size.
If the cat emoji appears cut off, you can resize the button to fit the content:
Make sure the button is selected.
From the menu, select Editor > Size to Fit Content or use the keyboard shortcut Command-=.
The canvas should now look something like the image to the left.

Duplicate the cat button to create the dog button:
Select the cat button.
Select Edit > Duplicate from the menu or use the keyboard shortcut, Command-D.
Move the new button to the right of the cat button.
Change the title of the button to the dog emoji .
Repeat the steps above to create a button that uses the cow emoji as​
its title. Move the cow button to the right of the dog button.
The canvas should now look similar to the first image in the gallery to the left.
Create a stack view that contains the three animal buttons:
Select all three buttons.
Click the Stack button at the bottom of the Interface Builder editor.
In the Attributes inspector, set the stack view Alignment to Center and Spacing to 18.
Because you arranged the buttons side by side when you created the ​
stack view, they automatically stack along the horizontal axis. You can change the axis of any stack view at any time in the Attributes inspector.
The canvas should now look similar to the second image in the gallery.

42
Q

Create the Rest of the Interface

A

The user interface of the app will consist of the following, from top to bottom:
A label to display the animal sound
A horizontal stack view of animal buttons
A label providing instructions to the user
Drag labels from the library pane onto the canvas, placing one label above the row of buttons and another below the buttons.
Change the text of the top label to “Animal Sounds.”
Change its font size to 24.
Change the text of the bottom label to “Tap an animal.”
Select both labels and the horizontal stack view, then click the Stack button to create a stack view.
Set the Alignment of the stack view to Center and the Spacing to 10.
If you need help with any of these tasks, refer to the previous part of this lesson.

43
Q

Adding Constraints

A

Just like in ElementQuiz, you need to add constraints to center the vertical stack view.
Select the stack view.
Add constraints to center the stack view horizontally and vertically.
Use the Resolve Auto Layout Issues menu to update frames.
This is the same process you’ve done before, so refer back to the previous part of this lesson if you need to look up the details.

44
Q

Checkpoint

A

The layout of the user interface is finished. This is a good time to make ​
sure it will adapt correctly. Choose different devices to change the size of ​
the canvas. Also change the orientation from portrait to landscape.
Just like with the ElementQuiz app, the constraints keep the stack view centered, and the stack view keeps its contents laid out properly. Plus, the horizontal stack view keeps the buttons centered and spaced properly.

45
Q

Writing the Code

A

When the user taps an animal button, your code will update the top label view and will play a sound corresponding to the animal.
Start by using actions and outlets for the text in the top label view.
Create an outlet named animalSoundLabel for the top label view.
Create an action named catButtonTapped() connected to the cat button.
Create an action named dogButtonTapped() connected to the dog button.
Create an action named cowButtonTapped() connected to the cow button.
Note: If you need to refresh your memory on how to create actions and outlets, see the Actions and Outlets lesson for step-by-step instructions.
Now you can add code to catButtonTapped() to set the text of animalSoundLabel .
@IBAction func catButtonTapped(_ sender: ​
AnyObject) { ​
animalSoundLabel.text = “Meow!” ​
}
Add similar code to dogButtonTapped() and cowButtonTapped() to set the text to “Woof!” for the dog and “Moo!” for the cow.

46
Q

Checkpoint

A

This is a good time to build and run the app to see if it’s behaving as expected. Tapping an animal button should make the correct text appear in the top label. The user interface should be centered on the screen, no matter what device you’re running on.

47
Q

Playing Sounds

A

Now you need to have your app play a short sound every time the user taps an animal button. iOS provides a number of ways to play sounds and work with audio.
To perform this relatively simple task, you’ll use an API provided by SimpleSound, a Swift class you’ll add to your project.
To use SimpleSound, you’ll do the following:
Add the SimpleSound.swift file to the app project in Xcode.
Add sound files to the app project in Xcode.
Create a SimpleSound instance using the name of the sound file:
let sound = SimpleSound(named: “moo”)
Call the play() method to play the sound:
sound.play()

48
Q

Adding Files

A

In the Finder, go to the Class Resources folder and locate a folder named AnimalSounds. You’ll find SimpleSound.swift and three sound files: Meow.m4a, Woof.m4a, and Moo.m4a.
Drag the files from the Finder to the project navigator.
In the sheet that appears, choose “Copy items if needed” and make sure ​
the checkbox for AnimalSounds is selected in the “Add to targets” section:

49
Q

Writing the Code

A

Now that you have access to the SimpleSound class and some animal sounds, you can write the code.
Create a constant property in ViewController.swift for the meow sound:
let meowSound = SimpleSound(named:”meow”)
Add two more constant properties, woofSound and mooSound. The names ​
of the sound files are “woof” and “moo.“
Next, write code to play “meow” when the cat button is tapped:
@IBAction func catButtonTapped(_ sender: AnyObject) {​
animalSoundLabel.text = “Meow!”​
meowSound.play()​
}
Add similar code to dogButtonTapped() and cowButtonTapped() to play the appropriate animal sounds.

50
Q

Testing

A

Make sure the volume is turned up on the device—or on the Mac, if you’re running in the simulator.
Build and run your app. When you tap each animal button, the text in the top label should change and the animal sound should play.

You can use what you’ve learned to build adaptive user interfaces in apps of your own. Here are some guidelines to follow:
Design for the smallest device. This will ensure your design will fit on other (larger) devices.
Use constraints to define the height and width of image views. This will prevent you from needing to resize an image view to accommodate a very large image.
Start by adding views and arranging them, then select the views and create a stack view.
Use stack view settings, like spacing and alignment, to create a wide variety of interface effects.
Nest stack views to create more complex user interfaces. Always try to start with the innermost stack views.
Use constraints to center the outermost stack view horizontally and vertically to ensure your user interface is centered on all devices.
Resolve Auto Layout issues after adding constraints. Select Update Frames in the Resolve Auto Layout Issues menu to get rid of those wiggly orange lines.
With these guidelines you’ll be able to create a wide variety of user interfaces for your apps.