[英]Custom NSToolbarItem Button Not Showing
我在应用程序的工具栏中有两个自定义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类型。 我尝试遵循的示例在此处: NSToolbar项目中的NSButton:单击问题
有经验的人可以提供建议吗?
我不知道为什么,但是:
[NSToolbarItem initWithCoder:]
调用[NSToolbarItem setImage:]
,然后在您设置为工具栏项目视图的按钮上调用[NSButton setImage:]
。 这会抹去您所做的一切。
您引用的示例不将NSToolbarItem
子类NSToolbarItem
。
我建议您也不要子类化NSToolbarItem
,而是通过接口构建器将常规NSToolbarItem
添加到工具栏,然后在awakeFromNib
通过其项目标识符找到该工具栏项目并将按钮设置为其视图。
我已经证实,以这种方式执行此操作符合预期。
我不理解为什么您的示例不起作用。 但是我以自己的方式制定了自定义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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.