Search code examples
swiftmacosswiftui

Perform an action when the Escape key is pressed (sheet)


In my code, I have a sheet. There are two buttons inside, each returning an essential value; however, the sheet can be closed by Escape. So I'm looking to perform an action when pressed this key is pressed, to return a value in every case.

Here's my code: the compiler the compiler gets stuck and doesn't build my app...

VStack {
// some content
}
.sheet(isPresented: $showSheet, content: {
// some content
})
.onKeyPress { key in
    if key == .escape {
         NSApplication.shared.reply(toApplicationShouldTerminate: false)
    }
}

Same issue:

VStack {
// some content
}
.sheet(isPresented: $showSheet, content: {
     VStack {
     // some content
     }
     .onKeyPress { key in
         if key == .escape {
              NSApplication.shared.reply(toApplicationShouldTerminate: false)
         }
     }
})

Do you have any idea what's wrong in my code?


Solution

  • Pressing the escape key in a sheet is the same thing as dismissing the sheet so implement a closure/function for the onDismiss parameter

    .sheet(isPresented: $showSheet, onDismiss: {
        // handle dismiss
    }, content: {
        // some content
    })