Cocoa 以编程方式将关闭按钮添加到窗口

Cocoa 以编程方式将关闭按钮添加到窗口,cocoa,button,nswindow,Cocoa,Button,Nswindow,我想以编程方式向NSWindow添加一个关闭按钮。我可以让按钮显示,但没有鼠标悬停或鼠标下降的效果。当我点击按钮时,我的“选择器”似乎从未被调用。我真的不知道是什么问题,为什么这么烦人 这就是我一直在搞的事情: closeButton = [NSWindow standardWindowButton:NSWindowCloseButton forStyleMask:self.styleMask]; NSView *themeFrame = [[self contentView] supervi

我想以编程方式向
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
问题似乎在于呼叫:
[姓名添加子视图:关闭按钮]

其中主题名为:
[[self contentView]superview]
只需将按钮添加到
[self contentView]
即可,但我希望将其添加到标题栏中

请不要使用界面生成器…

潜在问题#1)

我觉得您调用“
NSSelectorFromString
”的方式不正确。我不认为在目标C中可以通过这种方式传递参数

试试这个:

[closeButton setAction: @selector(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];
}

不知道
NSSelectorFromString
本身是否有问题,但方法签名中缺少冒号,这本身可能会导致问题。谢谢您的回答。我已经添加了建议修复并更新了原始问题,但是问题仍然存在。具体来说:将“我的”按钮添加到[self-contentView]工作时,该按钮可以调用选择器。但是,将其添加到[[self-contentView superview]]会导致无法单击的按钮(无选择器调用)。我希望这个按钮出现在标题栏中,而不是内容视图中。可以使用SelectorFromString,尽管@selector()更简单