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

时间:2011-05-25 18:41:41

标签: macos cocoa nscontrol

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

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

disabled enabled

1 个答案:

答案 0 :(得分:6)

您可以使用NSWindow的keyWindow属性,如果您想检查您的控件是否是键盘事件的第一响应者,也请测试[[self window] firstResponder] == self。我不相信keyWindow支持KVO,但您可以监听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];
}