How to add popup menu to NSToolbarItem?

I am trying to open a popup menu from NSToolbarItem. I tried using this example, but I can’t use this class method because NSToolbar and NSToolbarItem inherit from NSObject and not from NSView.

Besides creating a custom view, what is the best way to open a popup menu from NSToolbarItem?

+3
source share
5 answers

FYI: this post is long, but I'm just browsing, and I have an easy way for this, so I thought I would give an answer if someone else views it. I found that I cannot drag the popup directly onto the toolbar in Interface Builder from the Library. However, I can drag the popup out of the window onto the toolbar. So I first create a popup in the window and then drag it to the toolbar ... it works! Same thing with other objects.

+3
source

Just create NSView in IB with your menu as you want. Then in your window controller add the following code:

// This assumes you have a window property pointing to the window to which you'll
// add the toolbar. It also assumes you've connected the NSView to add to the
// toolbar to a member called toolbarView.

- (NSArray*)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar {
    return [NSArray arrayWithObject:@"myToolbarMenu"];
}

- (NSArray*)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar {
    return [self toolbarAllowedItemIdentifiers:toolbar];
}

- (NSToolbarItem*)toolbar:(NSToolbar*)toolbar
    itemForItemIdentifier:(NSString*)str
willBeInsertedIntoToolbar:(BOOL)flag
{
    if ([str isEqualToString:@"myToolbarMenu"] == YES) {
        NSToolbarItem* item = [[NSToolbarItem alloc] initWithItemIdentifier:str];
        [item setView:toolbarView];
        [item setMinSize:[toolbarView frame].size];
        [item setMaxSize:[toolbarView frame].size];
        return [item autorelease];  
    }
    return nil;
}

- (void)windowDidLoad {
    NSToolbar* toolbar = [[NSToolbar alloc] initWithIdentifier:@"myToolbar"];
    [toolbar setDelegate:self];
    [self.window setToolbar:[toolbar autorelease]];
}
+3
source

, - NSButton, NSMenu, NSToolbarItem setView:, .

+3

, NSPopUpButton.

Interface Builder 3.2.1 ( , ), nib . IB .

+3

Assuming what menuis an object NSMenu, and senderis NSToolbarItem, then all you have to do is pass in sender.viewto display the menu. No need to add another view if you have already configured NSToolbarItemthrough Interface Builder.

[NSMenu popUpContextMenu:menu
               withEvent:[NSApp currentEvent]
                 forView:sender.view];
0
source

Source: https://habr.com/ru/post/1718930/


All Articles