NSPanel没有成为关键窗口

时间:2012-07-20 12:36:29

标签: objective-c cocoa

我有一个NSPanel,我想将其设置为keyWindow,以便发布NSWindowDidBecomeKeyNotification,但即使在调用makeKeyWindow方法时,也不会发布通知。下面是我的代码,但我无法弄清楚它有什么问题:

newPanel = [[NSPanel alloc]initWithContentRect:windowRect
                                         styleMask:NSUtilityWindowMask
                                           backing:NSBackingStoreBuffered 
                                             defer:FALSE];

    [[NSNotificationCenter defaultCenter]addObserver:self 
                                            selector:@selector(test:) 
                                                name:@"NSWindowDidBecomeKeyNotification" 
                                              object:newPanel];
    // Create a slider and add to the panel
    NSSlider *slider = [[NSSlider alloc]initWithFrame:NSMakeRect(0, 0, windowRect.size.width, windowRect.size.height)];
    [[newPanel contentView]addSubview:slider];
    // Set window attributes
    [newPanel setHasShadow:TRUE];
    [newPanel setFloatingPanel:TRUE];
    [newPanel setReleasedWhenClosed:TRUE];
    [newPanel setHidesOnDeactivate:TRUE];
    [newPanel setBecomesKeyOnlyIfNeeded:NO];
    [newPanel makeKeyWindow];
    [newPanel makeFirstResponder:slider];
    [newPanel orderFront:sender];

现在当我打电话给[newPanel makeKeyWindow];时,应该发布NSWindowDidBecomeKeyNotification,并且应该调用-(void)test:(NSNotification*)aNotification。但它没有被召唤。

1 个答案:

答案 0 :(得分:1)

我将您的代码复制并粘贴到一个新项目中,它甚至没有显示面板,是否适合您?我可以通过创建一个属性thePanel(编译器不喜欢名称newPanel,不确定原因)并将thePanel的所有引用更改为self.thePanel来使其工作。我还将NSTitledWindowMask添加到样式掩码参数(styleMask:NSUtilityWindowMask | NSTitledWindowMask),并将makeKeyWindow命令移动到orderFront命令之后,或者将这两个命令替换为makeKeyAndOrderFront:self.window。