Search code examples
objective-cmacoscocoamacos-sierranstouchbar

Can I attach an NSTouchBar to an NSWindow after it's been created with no specific NSTouchBar support?


I'm using SDL to create a window for use with OpenGL and the only information it gives back is the NSWindow object.

Can I use that to then subsequently associate an NSTouchBar with that window?

I've successfully done it by directly modifying the SDL code to do it in the ViewController, but as a user of the library API, that option isn't available to me.

I was previously thinking I could do so with a customer NSResponder, but am no longer convinced this is a valid option.

Thank you.


Solution

  • Creating an NSWindowController and attaching it to the existing window works.

    @interface WindowController : NSWindowController <NSTouchBarDelegate>
    

    and

    - (id)init:(NSWindow *) nswindow
    {
        self = [super initWithWindow:nswindow];
        return self;
    }
    
    - (NSTouchBar *)makeTouchBar
    {
            NSTouchBar *bar = [[NSTouchBar alloc] init];
            bar.delegate = self;
            bar.customizationIdentifier = PopoverCustomizationIdentifier;
            bar.defaultItemIdentifiers = @[PopoverItemIdentifier, NSTouchBarItemIdentifierOtherItemsProxy];
            bar.customizationAllowedItemIdentifiers = @[PopoverItemIdentifier];
            bar.principalItemIdentifier = PopoverItemIdentifier;
            return bar;
    }
    

    You can see https://developer.apple.com/library/content/samplecode/NSTouchBarCatalog/Listings/Objective_C_NSTouchBar_Catalog_TestViewControllers_PopoverViewController_m.html for a bunch more of the guts to put in these functions.