2012-06-25 81 views
3

我想以編程方式向NSWindow添加關閉按鈕。我可以讓按鈕顯示,但沒有鼠標懸停或鼠標放下的效果。當我點擊按鈕時,我的「選擇器」似乎永遠不會被調用。我不確定最新的錯誤,以及爲什麼這麼煩人。以編程方式向NSWindow添加關閉按鈕

這裏是我一直在搞亂:

closeButton = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:self.styleMask]; 

NSView *themeFrame = [[self contentView] superview]; 
NSRect c = [themeFrame frame]; // c for "container" 
NSRect aV = [closeButton frame]; // aV for "accessory view" 
NSRect newFrame = NSMakeRect(            c.size.width - aV.size.width - 5, // x position            c.size.height - aV.size.height - 5, // y position           aV.size.width, // width            aV.size.height); // height 

[closeButton setFrame:newFrame];  
[themeFrame addSubview:closeButton]; 
[closeButton setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin]; 
[closeButton setEnabled:YES]; 
[closeButton setTarget:self]; 
[closeButton setAction:NSSelectorFromString(@"testClick:") ]; 

其中「testClick」只是我的課的memeber功能,並定義爲這樣:

- (void)testClick:(id)sender 

這個問題似乎打電話給:
[themeFrame addSubview:closeButton];

其中themeFrame是:[[self contentView] superview]只需將按鈕添加到[self contentView]工程,但我希望它添加到標題欄。

沒有Interface Builder中,請...

回答

0

潛在問題#1)

你打電話的方式 「NSSelectorFromString」 似乎不正確我。我不認爲你可以在Objective C.

通過這種方式傳遞參數試試這個:

[closeButton setAction: @selector(closeWindow:)]; 

,並創建一個新的「closeWindow:」行動,看起來像:

- (void) closeWindow: (id) sender; 

這關閉窗口。

潛在問題#2)

相反的:

closeButton = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:self.styleMask]; 
NSView *themeFrame = [[self contentView] superview]; 

爲什麼不使用:

NSWindow * parentWindow = [[self contentView] window]; 
if(parentWindow) 
{ 
    closeButton = [parentWindow standardWindowButton:NSWindowCloseButton forStyleMask:self.styleMask]; 
} 
+0

不知道'NSSelectorFromString'本身不好,而是冒號缺少方法簽名,這本身可能會導致問題。 – Monolo

+0

感謝您的答案。我已經添加了建議修正並更新了原始問題,但問題仍然存在。具體來說:將我的按鈕添加到[self contentView]工程中,按鈕可以調用選擇器。然而,將它添加到[[self contentView superview]]會產生一個無法點擊的按鈕(無選擇器調用)。我希望這個按鈕出現在標題欄中,而不是在內容視圖中。 – chris

+0

NSelectorFromString很好用於此,雖然@selector()更容易 –

相關問題