Your First iOS & SwiftUI App: Polishing the App

Mar 1 2022 · Swift 5.5, iOS 15, Xcode 13

Part 4: A Second Screen

36. Display a Second Screen

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: 35. Intro to Size Classes Next episode: 37. Intro to Swift Arrays
Transcript: 36. Display a Second Screen

So far, Bullsye has been a single “screen” of content: ContentView. Now, we want to make Bullsye transition to a differnet “screen” of content when you tap the Leaderboard button: LeaderboardVIew.

Let’s take a look at one way we can do this with SwiftUI, by using View’s sheet() method.

Pull up developer documentation, in SwiftUI\Views and Controls\View\View Presentation\sheet.

Open BackgroundView.swift. Add to top of TopView:

@State private var leaderboardIsShowing = false

Modify the Button as follows:

Button(action: {
  leaderboardIsShowing = true
}) {
  RoundedImageViewFilled(systemName: "list.dash")
}
.sheet(
  isPresented: $leaderboardIsShowing,
  onDismiss: { },
  content: {
    LeaderboardView()
  })

Build & run. Show how on portrait, the “sheet” look makes it appear on top, and you can swipe down to dismiss. But this doesn’t work on landscape, so we need to hook up the X button to dismiss the leaderboard.

Add to top of LeaderboardView.swift’s LeaderboardView:

@Binding var leaderboardIsShowing: Bool

Also HeaderView:

@Binding var leaderboardIsShowing: Bool

Set to false in the Button’s action:

leaderboardIsShowing = false

Modify LeaderboardView to pass leaderboardIsShowing:

HeaderView(leaderboardIsShowing: $leaderboardIsShowing)

Fixup previews:

struct LeaderboardView_Previews: PreviewProvider {
  static private var leaderboardIsShowing = Binding.constant(true)

  static var previews: some View {
    LeaderboardView(leaderboardIsShowing: leaderboardIsShowing)
      .environment(\.horizontalSizeClass, .compact)
    LeaderboardView(leaderboardIsShowing: leaderboardIsShowing)
      .previewLayout(.fixed(width: 568, height: 320))
    LeaderboardView(leaderboardIsShowing: leaderboardIsShowing)
      .preferredColorScheme(.dark)
      .environment(\.horizontalSizeClass, .compact)
    LeaderboardView(leaderboardIsShowing: leaderboardIsShowing)
      .previewLayout(.fixed(width: 568, height: 320))
      .preferredColorScheme(.dark)
  }
}

Back in BackgroundView.swift’s TopView, pass it along as well:

LeaderboardView(leaderboardIsShowing: $leaderboardIsShowing)

Build and run. Show that by tapping the x button it now dismisses.