Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: SwiftUI Data

13. Challenge: SwiftUI State

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 12. SwiftUI State Next episode: 14. SwiftUI Bindings
Transcript: 13. Challenge: SwiftUI State

Guess what - it’s time for your next coding challenge!

Your challenge is to pause the video, and add another button to the screen that says “Knock, Knock”. If you tap the button, the app should pop up a message that says “Who’s There?” in its title, and a knock knock joke of your choice in the message and dismiss button. I hope you have your best jokes ready!

Let’s review what you need to do for this:

First, open the SwiftUI canvas, open the library, and drag a button into the app, below the “Hit Me” button but still within the main VStack. Change its content to a text view that says “Knock Knock”.

Then, write some code to display a popup that says “Who’s There?”. Luckily, you already have an example of exactly how to do this:

You already have an example of how to add a state property to your ContentView struct. You can copy and paste this, and rename it to whosThereIsVisible.

You also already have an example of how to run some code when a button is tapped - by putting it inside the action block. This is where you wan to set whosThereIsVisible to true.

Finally, you already have an example of how to present an alert. Just follow this example to use whosThereIsVisible and present a knock knock joke instead.

Allright that’s it - now pause the video, and good luck.

Add Knock Knock button with SwiftUI canvas, set text to:

Text("Knock Knock")

Add whos there property:

@State private var whosThereIsVisible: Bool = false

Set it to true in the button’s action:

self.whosThereIsVisible = true

Add alert as follows:

.alert(isPresented: $whosThereIsVisible) {
  return Alert(
    title: Text("Who's There?"),
    message: Text("Little old lady."),
    dismissButton: .default(Text("Little old lady who?")))
}