我的代码如下:
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)
}
}
用于检测 macOS 应用程序中的按键。它检测按键,但由于某种原因,它没有设置
keycode
@Binding
变量,即值在 'before' 和 'after' 打印语句中不会改变。这怎么可能?
为了澄清起见,我在
keycode
期间传入的 init
变量是一个 @State
变量:
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)
....
}
}
@Binding
变量必须绑定到某些东西(例如@State
),比如
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)
}
}
}
如果没有绑定它只是提供自己的初始状态,将其视为外部存储,所以如果没有绑定则没有地方存储值,所以只能返回默认值。