Login required for access
In order to watch this lesson, you'll need to login to the website.

When building an application that supports data entry, you'll almost always need to include a modal form of some kind. In this lesson, we'll look at presenting a modal using the fullScreenCover modifier. In addition to this, I will also show various ways of dismissing these types of modals with @Binding vs Environment(.presentationMode).

Main View
struct MainView: View {    // 1    @State private var shouldPresentAddCardForm = false        var body: some View {        NavigationView {            ScrollView {                                // ....                                // 2                Spacer()                    .fullScreenCover(isPresented: $shouldPresentAddCardForm, onDismiss: nil) {                        AddCardForm()                    }            }            // ...        }    }
  1. Declare a @State variable that controls whether or not our fullScreenCover is presented.
  2. Attach a .fullScreenCover modifier to an empty Spacer() component.

struct AddCardForm: View {    // 1    @Environment(\.presentationMode) var presentationMode        @State private var name = ""        var body: some View {        NavigationView {            Form {                Text("Add card form")                TextField("Name", text: $name)            }            .navigationTitle("Add Credit Card")            .navigationBarItems(leading: Button(action: {                // 2                presentationMode.wrappedValue.dismiss()            }, label: {                Text("Cancel")            }))        }    }}
  1. The SwiftUI framework engine will automatically inject this view with the proper Environment variables whenever appropriate. Because we're presenting this view as a fullScreenCover, presentationMode can be used to dismiss itself later.
  2. Call dismiss() on presentationMode's wrappedValue. As mentioned in the video, using this logic is better than declaring a @Binding dependency on this view. Views in SwiftUI should be kept as "dumb" as possible.

Comments (0)