设置@Binding变量由于某种原因不会更改变量

问题描述 投票:0回答:1

我的代码如下:

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)
        ....
    }
}
swift macos swiftui
1个回答
4
投票

@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)
            }
    }
}

如果没有绑定它只是提供自己的初始状态,将其视为外部存储,所以如果没有绑定则没有地方存储值,所以只能返回默认值。

© www.soinside.com 2019 - 2024. All rights reserved.