0

我在应用程序的工具栏中有两个自定义 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:单击问题

有没有经验的人可以提供建议?

4

2 回答 2

1

我不知道为什么,但是:

[NSToolbarItem initWithCoder:]正在调用[NSToolbarItem setImage:],然后调用[NSButton setImage:]您设置为工具栏项视图的按钮。这会抹杀你所做的一切。

您所指的示例不属于子类NSToolbarItem

我建议您也不要子类化NSToolbarItem,而是NSToolbarItem通过界面构建​​器将常规添加到工具栏,然后awakeFromNib通过其项目标识符找到该工具栏项目并将按钮设置为其视图。

我已经验证这样做可以按预期工作。

于 2014-04-25T20:45:23.100 回答
0

我不明白为什么你的例子不起作用。但是我用自己的方式制定了自定义的 NSToolbarItem,甚至没有使用 NSToolbarDelegate。

我的方式是假设您在笔尖内构建工具栏,而不是使用代码(大部分)。

我正在做的是在我的 nib 中创建我自己的 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/

于 2016-02-27T16:01:01.933 回答