Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make embedded view controller part of the responder chain?

I am developing a Mac app using storyboards. I have a window that presents an NSViewController as its contents, which contains a "container view controller" that embeds an NSSplitViewController.

enter image description here

The expected behaviour is for the NSSplitViewController to be part of the responder chain, such that a menu item that triggers the toggleSidebar action on the first responder actually collapses the item of the NSSplitViewController that's marked as a sidebar.

However, this simply does not happen and the menu item remains disabled. So my question is, how can-I get the NSSplitViewController to be part of the responder chain?

like image 618
Abstract-Sky Avatar asked Dec 20 '17 21:12

Abstract-Sky


Video Answer


1 Answers

I noticed that maybe some of these solutions have worked, but i adapted a more general purpose answer from https://stackoverflow.com/a/30938725/6938357.

I made an extension on NSViewController to look for supplemental targets. Works on NSSplitViewController as well as any general NSViewController with child(ren).

extension NSViewController {

    open override func supplementalTarget(forAction action: Selector, sender: Any?) -> Any? {
        if let target = super.supplementalTarget(forAction: action, sender: sender) {
            return target
        }

        for child in children {
            var target = NSApp.target(forAction: action, to: child, from: sender) as? NSResponder

            if target?.responds(to: action) == false {
                target = child.supplementalTarget(forAction: action, sender: sender) as? NSResponder
            }

            if target?.responds(to: action) == true {
                return target
            }
        }

        return nil
    }
}

If you only want this to search on a single view controller, put this implementation there instead. This extension applies to all NSViewControllers and its subclasses.

like image 148
Procrastin8 Avatar answered Sep 26 '22 02:09

Procrastin8