๐Ÿ“ฆdismiss

SwiftUI โŸฉ view โŸฉ environment โŸฉ value โŸฉ dismiss

An action that dismisses the current presentation.

@Environment(\.dismiss) var dismiss

Use this environment value to get the DismissAction instance for the current Environment. Then call the instance (dismiss()) to perform the dismissal.

You call the instance directly because it defines a callAsFunction() method that Swift calls when you call the instance. You can use this action to:

  • dismiss a modal presentation, like a sheet or a popover.

  • pop the current view from a NavigationStack.

struct CreatureEditor: View {
    
    @State var newCreature = Creature(name: "", emoji: "") // new creature to add to data
    @EnvironmentObject var data : Zoo                      // data model
    
    // โญ๏ธโญ๏ธโญ๏ธ allow the app to dismiss the current view
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        VStack(alignment: .leading) {
        
            Form { ... }    // for editing new creature
            
            Button("Add") { 
                // add new item to data
                data.creatures.append(newCreature)
                
                // โญ๏ธ dismiss current view
                dismiss()
            }
            
        }// VStack
    }
}

Last updated