0

I want to restore a window position of my Cocoa app whenever an user launches the app. This feature is implemented in default in Cocoa. However, I also want to make my app terminated by tapping the red x button on the top-left corner on the toolbar, so I wrote the following in AppDelegate.swift:

func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
    return true
}

This makes the app quit immediately by tapping the red x button. However, if you terminate the app in this way, the window doesn't restore to the previous state the next time you open the app.

Why does the app not restore when you terminate the app by closing the window? And how can I restore even if the user terminates the app by closing the window?

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
Blaszard
  • 30,954
  • 51
  • 153
  • 233
  • Which mechanism are you using to restore the window position when it's quit in other ways? Frame autosave name? – Ken Thomases Feb 01 '15 at 10:36
  • @KenThomases I don't use anything. The window is restored in default when you quit the app by tapping ⌘+Q, I think. – Blaszard Feb 01 '15 at 11:16
  • Your windows are restored if 1: you have the "restorable" box checked in IB, (which you do, based on your comments), and 2: the window is STILL OPEN when you quit the app. If you close the window *before* quitting, the position is not restored. In your situation, you have already closed the window, so the state is not restored. – zeppenwolf Feb 01 '15 at 19:21
  • @zeppenwolf I confirmed that the *restorable* checkbox is set in IB. As to 2), thank you for the tips! – Blaszard Feb 02 '15 at 13:49

2 Answers2

0

You can do it in 2 ways

1) You can save the window's frame to plist when window's delegate fire the close and reposition the window in that frame when its open again.

2) This way like Zeppenwolf comment , you can return NO to windowShouldClose and call the app terminate in a delay.

Sheen Vempeny
  • 818
  • 1
  • 5
  • 8
0

Based on the comment of zeppenwolf I implemented the following in my NSWindowDelegate

- (BOOL)windowShouldClose:(NSWindow *)sender {
    [[NSOperationQueue currentQueue] addOperationWithBlock:^{
        [NSApp terminate:sender];
    }];

    return NO;
}
Julian F. Weinert
  • 7,474
  • 7
  • 59
  • 107