我在应用程序的工具栏中有两个自定义NSToolbarItems。每个类都有一个NSButton,我在其中设置按钮,然后将工具栏项的视图设置为按钮(例如停止按钮项):
@implementation RBSStopButtonToolbarItem
@synthesize button = _button;
-(id)initWithItemIdentifier:(NSString *)itemIdentifier
{
self = [super initWithItemIdentifier:itemIdentifier];
if(self)
{
// create button
_button = [[NSButton alloc] init];
// set the frame and bounds to be the same size
//[_button setFrameSize:NSMakeSize(64.0, 64.0)];
//[_button setBoundsSize:NSMakeSize(64.0, 64.0)];
// button will not have a visible border
[_button setBordered:NO];
// set the original and alternate images...names are "opposite"
[_button setImage:[NSImage imageNamed:@"StopButtonAlternateIcon"]];
[_button setAlternateImage:[NSImage imageNamed:@"StopButtonIcon"]];
// image position
[_button setImagePosition:NSImageOnly];
// set button type
[_button setButtonType:NSMomentaryChangeButton];
// button is transparent
[_button setTransparent:YES];
// set the toolbar item view to the button
[self setView:_button];
}
return self;
}
我为每个自定义NSToolbarItem都有一个IBOutlet:
// toolbar item for start button
IBOutlet RBSStartButtonToolbarItem *_startButtonToolbarItem;
// toolbar item for stop button
IBOutlet RBSStopButtonToolbarItem *_stopButtonToolbarItem;
但是我没有在自定义视图工具栏项中看到图像:
图像是.icns类型。我试图遵循的例子如下:
NSButton in NSToolbar item: click issue
有没有经验可以提供建议的人?
答案 0 :(得分:1)
我不知道为什么,但是:
[NSToolbarItem initWithCoder:]
正在调用[NSToolbarItem setImage:]
,然后在您设置为工具栏项目视图的按钮上调用[NSButton setImage:]
。这抹去了你所做的一切。
您所指的示例并非子类NSToolbarItem
。
我建议您也不要继承NSToolbarItem
,而是通过界面构建器将常规NSToolbarItem
添加到工具栏,然后在awakeFromNib
中通过其项目标识符找到该工具栏项目将按钮设置为视图。
我已经确认以这种方式按预期工作。
答案 1 :(得分:0)
我不遵循为什么你的例子不起作用。 但是我已经用自己的方式制定了自定义NSToolbarItem,甚至没有使用NSToolbarDelegate。
我的方法是假设您在笔尖内构建工具栏而不是代码(主要是)。
我正在做的是在我的笔尖中创建我自己的NSView,无论我想要什么。 然后我将这个NSView拖入我的笔尖中的NSToolbar。 xCode会自动将NSView放在NSToolbarItem中。 然后,您可以将此自定义NSToolbarItem拖动到默认项目中,并将其放置在您想要的任何顺序(因此您甚至不需要通过代码放置它)。
棘手的部分是将NSToolbarItem子类化,然后在这个特定NSToolbarItem子块的awakeFromNib中,将它的视图设置为它下面的NSView。 您还需要将NSView引用到该子类中的IBOutlet * NSView。
这是子类的代码。
标题文件:
#import <Cocoa/Cocoa.h>
@interface CustomToolbarItem : NSToolbarItem
{
IBOutlet NSView * customView;
}
@end
Obj-c文件:
#import "CustomToolbarItem.h"
@implementation CustomToolbarItem
-(instancetype)initWithItemIdentifier:(NSString *)itemIdentifier
{
self = [super initWithItemIdentifier:itemIdentifier];
if (self)
{
}
return self;
}
-(void)awakeFromNib
{
[self setView:customView];
}
@end
我还写过一篇关于我是如何做到这一点的博客文章:
http://pompidev.net/2016/02/24/make-a-custom-nstoolbar-item-in-xcodes-interface-builder/