Make a Cocoa application quit when the main window is closed?

后端 未结 5 1000
日久生厌
日久生厌 2021-02-05 05:18

How to make a Cocoa application quit when the main window is closed? Without that you have to click on the app icon and click quit in the menu.

相关标签:
5条回答
  • 2021-02-05 05:34

    You should have an IBOutlet to your main window. For Example: IBOutlet NSWindow *mainWindow;

    - (void)awakeFromWindow {
        [mainWindow setDelegate: self];
    }
    - (void)windowWillClose:(NSNotification *)notification {
        [NSApp terminate:self];
    }
    

    If this does not work you should add an observer to your NSNotificationCenter for the Notification NSWindowWillCloseNotification. Don't forget to check if the right window is closing.

    0 讨论(0)
  • 2021-02-05 05:38

    This works for me.

    extension MainWindowController: NSWindowDelegate {
        func windowWillClose(_ notification: Notification) {
            if let window = notification.object as? NSWindow, let controller = window.windowController {
    
                if window == self.window {
    
                    for window in self.childWindows {
    
                        print(" Closing \(window)")
                        window.close()
    
                    }
    
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-05 05:46

    As the question is mainly about Cocoa programming and not about a specific language (Objective-C), here is the Swift version of Chuck's and Steve's answer:

    @NSApplicationMain
    class AppDelegate: NSObject, NSApplicationDelegate {
    
        func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
            return true
        }
    
        // Your other application delegate methods ...
    
    }
    

    For Swift 3 change the method definition to

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
    
    0 讨论(0)
  • 2021-02-05 05:47

    You can implement applicationShouldTerminateAfterLastWindowClosed: to return YES in your app's delegate. But I would think twice before doing this, as it's really unusual on the Mac outside of small "utility" applications like Calculator and most Mac users will not appreciate your app behaving so strangely.

    0 讨论(0)
  • 2021-02-05 05:47

    Add this code snippet to your app's delegate:

    -(BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app {
        return YES;
    }
    
    0 讨论(0)
提交回复
热议问题