How to add NSViewController to a responder chain?

后端 未结 4 1986
谎友^
谎友^ 2020-12-05 15:27

I\'m having hard time understanding and finding info about how to make NSViewController accept key and mouse events. I read somewhere that in order to register these events

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 16:12

    While debugging. I noticed the NSViewController view does not accept the first responder.

    You can confirm this by printing print(viewController.view) //false

    for NSViewController to be added to the responder chain, its view must acceptFirstReponder. This could easily be done by creating an extension of NSView and overriding its acceptFirstResponder

    extension NSView{
        //making view acceptFirstResponder by default,
        //this will enable NSViewController receive responder event dispatched into responder chain
        open override var acceptsFirstResponder: Bool{return true}
    }
    

    With this, your controller will added to the responder chain and will receive all responder events.

    My explanation may not be too accurate as I am new to Cocoa. but the solution does work perfectly well.

    I did this to resolve issue of my ViewController not receiving onKeyDown event.

提交回复
热议问题