Search code examples
swiftmacosfullscreen

How can I get a notification when a window becomes full-screen in Swift?


I want to add a full-screen mode setting to my game. However, I need to automatically update the setting if the user manually toggles full-screen mode.

How do I run code as soon as fullscreen is toggled by any means? In other words, how can I receive a notification when the user clicks the green button at the top of the window to make it full-screen?

Without this information, I cannot figure out how to synchronize my application's full-screen mode setting with the UI provided by the operating system.


Solution

  • Using the code from the other answer, I was able to construct the code to do this:

    In applicationDidFinishLaunching:

    NotificationCenter.default.addObserver(forName: NSWindow.willEnterFullScreenNotification, object: nil, queue: OperationQueue.main, using: { note in
        print("Entered Fullscreen")
    })
    
    NotificationCenter.default.addObserver(forName: NSWindow.willExitFullScreenNotification, object: nil, queue: OperationQueue.main, using: { note in
        print("Exited Fullscreen")
    })