【问题标题】:Programmatically add a close button to an NSWindow以编程方式将关闭按钮添加到 NSWindow
【发布时间】:2012-06-26 08:26:12
【问题描述】:

我想以编程方式向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”只是我班级的一个成员函数,定义如下:

- (void)testClick:(id)sender

问题似乎是调用:
[themeFrame addSubview:closeButton];

themeFrame 所在的位置:[[self contentView] superview] 只需将按钮添加到 [self contentView] 即可,但我希望将其添加到标题栏中。

请不要使用界面生成器...

【问题讨论】:

    标签: cocoa button nswindow


    【解决方案1】:

    潜在问题 #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];
    }
    

    【讨论】:

    • 不知道NSSelectorFromString本身是否不好,但是方法签名中缺少冒号,这本身可能会导致问题。
    • 感谢您的回答。我添加了建议修复并更新了原始问题,但问题仍然存在。具体来说:将我的按钮添加到[self contentView] 作品中,按钮可以调用选择器。但是,将其添加到 [[self contentView superview]] 会导致按钮无法单击(没有选择器调用)。我希望这个按钮出现在标题栏中,而不是在内容视图中。
    • NSelectorFromString 可以用于此,尽管 @selector() 更容易
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多