A popup button with a static image (Cocoa OSX)

天涯浪子 提交于 2019-12-12 16:30:07

问题


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?


回答1:


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.




回答2:


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:


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




回答4:


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



来源:https://stackoverflow.com/questions/2669242/a-popup-button-with-a-static-image-cocoa-osx

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