A popup button with a static image (Cocoa OSX)

2019-07-19 06:46发布

I am trying to make a popup button that always displays a + as its image and when you click on it, a context menu pops up that will allow you to decide what type of object you want to add. Is there anyway to do this using an NSPopupButton? I saw in the specs for NSPopupButotn that the method SetImage has no effect so it seems that this is likely not going to work using this class. Is this correct?

4条回答
乱世女痞
2楼-- · 2019-07-19 07:00

Why not just use an NSPopupButton? Using 2 buttons to perform one task doesn't seem right plus as mentioned it doesn't behave in the normal manner regarding holding on the button.

To get the popup button working how you like... set it to be a pull-down type. Don't give the popup button itself any name or image. If the popup button doesn't have a name or image then the first menu item becomes the title of the button. Menu items can have images so don't give the first menu item any title, just set it's image and that's the image you'll see on the popup button. For the rest of the menu items, just add them as normal after the first menu item. Note that if you programmatically change the menu items in code, just make sure to leave the first menu item in tact and everything will be OK. I do this in a few of my applications with no problem.

查看更多
来,给爷笑一个
3楼-- · 2019-07-19 07:05

A popup button takes the Image & Title of the first menu-item in the menu associated with it. So its better to include the image, which you want to appear as you popup button, as first menu item and then hide its visibility.

If you aren't clear yet, then go through the following video once, it will surely make you understand.

This tutorial shows how to create a toolbar item (NSToolbarItem) with drop-down menu for NSToolbar in Interface Builder : Link

查看更多
We Are One
4楼-- · 2019-07-19 07:20

The key is to use NSPopUpButtonCell's setUsesItemFromMenu:. The Apple docs include an example of how to use this.

查看更多
一夜七次
5楼-- · 2019-07-19 07:24

Yes, the visible appearance of NSPopUpButton is wrong for what you want.

What you want is a regular NSButton with a menu attached. In Interface Builder clear the title, set the Bezel to Square, the Position to the center icon-only version and the image to NSAddTemplate.

Then create a NSPopUpButton, set it to "Pull Down", hidden, and align it/set its size to the bottom of the NSButton.

Finally, connect performClick: in the NSButton to performClick: on the NSPopUpButton.

That won't handle a click-hold on the button; for that you'll have to write some code to use a (non-drawing) NSPopUpButtonCell.

查看更多
登录 后发表回答