当窗口是否为关键时绘制NSControl

gca*_*amp 3 macos cocoa nscontrol

我有一个NSControl子视图,我想在控件不在keyWindow上时更改绘图.问题是我没有看到任何反映该状态的enabled属性(尝试过的财产但不是这样).

简单来说,我可以区分这两种状态吗?

残启用

Mar*_*eau 6

您可以使用NSWindow的keyWindow属性,如果您想检查您的控件是否是键盘事件的第一响应者也要测试[[self window] firstResponder] == self.我不相信keyWindow支持志愿,但有一个NSWindowDidBecomeKeyNotificationNSWindowDidResignKeyNotification你可以听.例如,

- (id)initWithFrame:(NSRect)frameRect;
{
    if ( self = [super initWithFrame:frameRect] )
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(display) name:NSWindowDidResignKeyNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(display) name:NSWindowDidBecomeKeyNotification object:nil];
    }

    return self;
}

- (void)drawRect:(NSRect)aRect;
{
    if ( [[self window] isKeyWindow] )
    {
    // one way...
    }
    else
    {
    // another way!
    }
}

- (void)dealloc;
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)