macoscocoanscontrol

Drawing NSControl when the windows is key or not


I have a NSControl subview and I want to change the drawing when the control is not on a keyWindow. The problem is that I don't see any property that reflects that state (tried enabled property but that was not it).

In simple terms, can I differentiate between these two states?

disabledenabled


Solution

  • You can use NSWindow's keyWindow property, and if you want to check to see if your control is the first responder for keyboard events also test [[self window] firstResponder] == self. I don't believe keyWindow supports KVO, but there is a NSWindowDidBecomeKeyNotification and NSWindowDidResignKeyNotification you can listen for. For instance,

    - (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];
    }