如何判断NSPanel何时获得焦点或成为关键?

问题描述 投票:1回答:1

我正在XCode4中编写一个Cocoa / Objective-C应用程序,我需要知道我的首选项面板何时打开。我需要像windowDidBecomeKey这样的回调;我试图遵循this question提供的解决方案,但windowDidBecomeKeywindowDidExpose都不是代表方法(但其他人,如windowDidLoadwindowWillLoad等)。

为了明确我的意思,“不要作为委托方法出现”,我的意思是当我开始输入方法名称时,它们不会显示在自动完成中。无论如何我确实尝试过定义它们,但它们从未被调用过。

NSPanel对象缺乏这些方法,还是有更多我需要做的事情?

目前,我有一个接口PrefWindowController

PrefWindowController.h:

#import <Cocoa/Cocoa.h>

@interface PrefWindowController : NSWindowController
    //Delegate methods like windowDidBecomeKey appear to not be available here
@end

PrefWindowController.m:

@implementation PrefWindowController

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        NSAlert *alert = [[[NSAlert alloc] init] autorelease];
        [alert setMessageText:@".."];
        [alert runModal];
    }

    return self;
}

- (void)windowDidLoad
{
    NSAlert *alert = [[[NSAlert alloc] init] autorelease];
    [alert setMessageText:@"Loaded"];
    [alert runModal];
}

@end

当窗口在应用程序启动时从.xib加载时,windowDidLoad将触发并显示上面定义的通知。我这样做只是为了测试方法实际上是被调用的。

有关如何在面板成为键或获得焦点时获得回调的任何建议将非常有帮助。

更新:

我在窗口控制器中添加了一个windowDidBecomeKey方法,如下所示:

PrefWindowController.h:

- (void)windowDidBecomeKey:(NSNotification *)notification;

PrefWindowController.m:

- (void)windowDidBecomeKey:(NSNotification *)notification
{
    NSLog(@"Test");
}

第一次打开窗口时会记录测试消息,但是在我的main.m文件的返回行中,我收到错误消息:

线程1:程序接收信号:“EXC_BAD_ACCESS”

objective-c cocoa xcode4 nswindowcontroller nspanel
1个回答
8
投票

NSWindowDelegate协议具有以下方法

- (void)windowDidBecomeKey:(NSNotification *)notification
- (void)windowDidResignKey:(NSNotification *)notification

所以你可以将NSWindowController设置为NSWindow委托来获得这个回调。您还可以注册这些通知:

NSWindowDidResignKeyNotification
NSWindowDidBecomeKeyNotification

NSPanel是NSWindow的子类,因此所有这些行为都适用于您的情况。

© www.soinside.com 2019 - 2024. All rights reserved.