[英]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.