我的代码如下:
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)
}
}
用于检测osx应用程序中的按键。它检测到按键,但是由于某种原因,它没有设置按键码@binding变量(即,“ before”和“ after”打印语句中的值没有改变),这怎么可能呢?
编辑:为澄清起见,我在初始化期间传递的键码变量是@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)
....
}
}
答案 0 :(得分:1)
@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)
}
}
}
如果未绑定,则仅提供自己的初始状态,将其视为外部存储,因此,如果没有绑定,则没有位置存储值,因此只能返回默认值。