swiftcocoaxcode-storyboardfirst-respondernstoolbar

How to send action from NSToolbar item to First Responder of TabViews


I want NSToolbar items of my Mac app to trigger actions of the first responder object. I have an app with the following storyboard layout:

enter image description here

As you can see there is a button (Test Action) in the window's toolbar. It is connected to an action function of the first responder object. The function itself is implemented in the first view controller of the TabView.

class ViewController: NSViewController {
    @IBAction func testAction(_ sender: Any) {
        print("testAction")
    }
}

However the action never gets triggered. If I put the same action in the TabViewController, it does get triggered.

If I set the nextRespodner property of the TabViewController to the ViewController, it doesn't help:

class TabViewController: NSTabViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        nextResponder = children.first // Does not help
    }
}

Somehow the responder chain does not work as I would expect it. Does anyone have a solution to this? Here's an example project for the issue: https://github.com/Iomegan/ResponderChainStoryboard


Solution

  • Add this to ViewController:

    override func viewDidAppear() {
        super.viewDidAppear()
        view.window?.makeFirstResponder(self)
    }