Skip Navigation

Question: How do I detect the delete key being pressed on macOS?

So I have a view that is focusable and has onKeyPress on it. I want to show a modal dialog when the user presses the delete key. However, it seems that the pressedKey.key for the delete key does not equal KeyEquivalent.delete value.

Example:

 swift
    
import SwiftUI

struct MyView: View {
    var body: some View {
        Rectangle()
            .frame(width: 100, height: 100)
            .focusable()
            .focusEffectDisabled()
            .onKeyPress { pressedKey in
                // Output: KeyEquivalent(character: "\u{7F}") == KeyEquivalent(character: "\u{08}")            
                print("\(pressedKey.key) == \(KeyEquivalent.delete)")
                return .handled
            }
    }
}

  

Am I missing something that is otherwise obvious?

2 comments