NSWindowDelegate windowShouldClose on Catalyst

Hi,

I'm looking for a way to do something when the user presses the window red close button on a Catalyst app. For example, in some cases, I need to display an alert and prevent the window from closing.

On AppKit we can use the windowShouldClose delegate method of NSWindowDelegate. Unfortnuately this is not available on Catalyst.

Did someone found a way on Catalyst to prevent a window from closing? Maybe there is a way to expose the AppKit NSWindowDelegate object?

Thank you

Replies

This is not currently possible. The AppKit NSWindowDelegate is an important part of the internal Mac Catalyst infrastructure, so you should not attempt to expose / replace it. Please file a request for an equivalent Mac Catalyst API using Feedback Assistant.

I solved this issue by creating an OSX Bundle for my catalyst app. Although I can set my Principal class within the bundle as an NSWindowDelegate, the delegate does not respond to the windowShouldClose function. Interestingly the NSApplicationDelegate that use to work pre Ventura will now crash the app under Ventura.

The only solution I could find was to override the close button and substitute my own action when the user presses the close button. In the Bundle's Principal Class:

    // schedule a timer to complete the setup - apparently
    // we need to stabilize the app before setting delegates
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false)
    {_ in
        let sharedApp        = NSApplication.shared
        
        // NSApplicationDelegate seems incompatible with the new Ventura
        // release so it is commented out now. If the NSApplicationDelegate
        // is activated then any main menu bar selection results in an
        // app crash.
        //            sharedApp.delegate   = self
        
        self.mainWindow           = sharedApp.windows.first
        self.mainWindow?.delegate = self
        
        // override the app close button as we can't use the app delegate's
        // applicationShouldTerminateAfterLastWindowClosed method or the
        // NSWindowDelegate's windowShouldClose method.
        let closeButton     = self.mainWindow?.standardWindowButton(NSWindow.ButtonType.closeButton)
        closeButton?.target = self
        closeButton?.action = #selector(self.terminateAppOverride(_close:)) 
    }
Post not yet marked as solved Up vote reply of waoz Down vote reply of waoz
  • confirmed this works

Add a Comment