Show NSPopover from NSToolbarItem Button

余生颓废 提交于 2020-05-10 09:46:04

问题


I want to show an NSPopover from an NSToolbarItem button in my toolbar.
(i.e. positioned below the button).

Ideally, I want to pass the NSView of the button to the popover to position it.
My question is, how do I get the NSView of the NSToolbarItem?

[toolbarbutton view] always returns nil.


回答1:


The answer appears to be in the video for the 2011 WWDC Session 113, "Full Screen and Aqua Changes." Basically, put an NSButton inside the NSToolbaritem and use the view of that.

A blog post is here: http://www.yellowfield.co.uk/blog/?p=33, and a sample project is on github at http://github.com/tevendale/ToolbarPopover

All in the sprit of http://xkcd.com/979!




回答2:


You can send the action directly from the NSButton enclosed in the NSToolbarItem (which is what you should generally do anyways, consider segmented controls, where each segment has its own target/action), and that will do the trick.




回答3:


Instead of getting the view from the IBAction sender, connect an IBOutlet directly to the toolbar item and use that to get the relative view:

In your header file:

@property (weak) IBOutlet NSToolbarItem *theToolbarItem;
@property (weak) IBOutlet NSPopover *thePopover;

In your implementation file, to show the popover:

[self.thePopover showRelativeToRect:[[self.theToolbarItem view] bounds] ofView:[self.theToolbarItem view] preferredEdge:NSMinYEdge];

This will also work for showing popups from menu item selections inside a toolbar item.




回答4:


While I did achieve that the Popover was shown using the approach mentioned by Stuart Tevendale, I did run into problems when I tried to validate (enable / disable) the NSToolbarItems using the NSToolbarDelegate:

-(BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem {
    BOOL enable = YES;

    NSString *identifier = [toolbarItem itemIdentifier];

    // This does never get called because I am using a button inside a custom `NSToolbarItem`
    if ([identifier isEqualToString:@"Popover"]) {
        return [self someValidationMechanism];
    } 

    // For this the validation works when I am using a standard `NSToolbarItem`
    else if ([identifier isEqualToString:@"StandardToolbarItem"]){
        return [self someOtherValidationMechanism];
    }

    return enable;
}

So I would advise not to display a Popover from NSToolbarItem. An alternative might be to show a Page Sheet: How to show a NSPanel as a sheet



来源:https://stackoverflow.com/questions/8142791/show-nspopover-from-nstoolbaritem-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!