My code is as follows:
class EditorWindow: NSWindow {
@Binding var keycode : Int
override func keyDown(with event : NSEvent) {
super.keyDown(with: event)
print("before", self.keycode, Int(event.keyCode))
self.keycode = Int(event.keyCode)
print("after", self.keycode, Int(event.keyCode))
}
init(keycode : Binding<Int>){
self._keycode = keycode
super.init(contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
}
}
for detecting key-presses in a macOS app. It detects the key-presses, but for some reason it doesn't set the keycode @Binding variable , i.e. the value doesn't change in the 'before' and 'after' print statements. How can this be possible?
Edit:
For clarification, the keycode variable I am passing in during init is a @State variable:
struct ContentView: View {
@State var keycode : Int = 0
...
}
...
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
...
func applicationDidFinishLaunching(_ aNotification: Notification) {
let contentView = ContentView(userData: UserData(text:""))
window = EditorWindow(keycode: contentView.$keycode)
....
}
}
ObservableObjectas @EnvironmentObject for ContentView and pass its reference into EditorWindow.