Reputation: 465
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?
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)
....
}
}
Upvotes: 5
Views: 791
Reputation: 257493
The @Binding
variable must be bound to something (eg. @State
), like
struct TestNSWindowBinding: View {
@State var keyCode: Int = 0
var body: some View {
Text("Current key: \(keyCode)")
.onAppear {
let window = EditorWindow(keycode: self.$keyCode)
window.makeKeyAndOrderFront(nil)
}
}
}
If it is not bound it just provide own initial state, consider it as external storage, so if no bound then no place to store value, so only default can be returned.
Upvotes: 4