2

I would like to change the background of an NSView depending on if the the window is focused.

I found this question: Change NSView background color when window has focus

And the first answer works fine except the redraw is not triggered when the windows loses or gains focus.

How can I trigger the redraw when the mainWindow changes?

Community
  • 1
  • 1
Laszlo Korte
  • 1,179
  • 8
  • 17

2 Answers2

2

In your NSWindow delegate:

func windowDidBecomeMain(notification: NSNotification) {
    let theView = ...
    theView.needsDisplay = true
}

func windowDidResignMain(notification: NSNotification) {
    let theView = ...
    theView.needsDisplay = true
}

In your NSView subclass:

func drawRect(rect: NSRect) {
    if self.window.isMainWindow {
        // draw active appearance
    } else {
        // draw inactive appearance
    }
}
Aderstedt
  • 6,301
  • 5
  • 28
  • 44
0

Use NSNotificationCenter's addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: to watch for NSWindowDidBecomeMainNotification and NSWindowDidResignMainNotification with the view's window as the object argument.

Zoë Peterson
  • 13,094
  • 2
  • 44
  • 64