objective-c - 自定义 NSToolbarItem 按钮未显示

标签 objective-c macos cocoa nstoolbar

我在应用程序的工具栏中有两个自定义 NSToolbarItems。每个类都有一个 NSButton,我在其中设置按钮,然后将工具栏项的 View 设置为按钮(例如停止按钮项):

@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;

但是我在自定义 View 工具栏项目中没有看到图像: missing images for toolbar items 图像是 .icns 类型。我尝试遵循的示例在这里: NSButton in NSToolbar item: click issue

有没有有经验的可以给点建议?

最佳答案

我不知道为什么,但是:

[NSToolbarItem initWithCoder:] 正在调用 [NSToolbarItem setImage:] ,然后在您拥有的按钮上调用 [NSButton setImage:]设置为工具栏项目的 View 。这会抹掉你所做的一切。

您引用的示例不是 NSToolbarItem 的子类。

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

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

关于objective-c - 自定义 NSToolbarItem 按钮未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232295/

相关文章:

objective-c - 询问 Cocoa/Objective-C 中的热键

ios - 轻按单元格时更改UICollectionViewCell的大小

c++ - 从 C++ 类方法调用 Objective-C 方法

iphone - ASIHttpRequest : requestDidFinishSelector vs. requestDidFailSelector

objective-c - Uncrustify 一次设置是否有最大缩进量?

macos - 如何为 Mac 安装 IBM i Access?

objective-c - 有没有办法运行两个或多个 NSTasks?

swift - 快速按下按钮时使用 slider

swift - CALayer 的属性 isGeometryFlipped 在 macOS 上不起作用

cocoa - 使用drawRect方法绘图 - Cocoa