swiftmacosnswindowautosave

How to restore window position in an OSX application?


I created a storyboard it has window view controller as initial view controller. I gave the window an autosave name preferencesWindow. In the preferences I checked [x] Restorable and [x] Release when closed.

When I go into the menu and click Preferences I load the window controller like so:

    let storyboard          = NSStoryboard(name: "Preferences", bundle: nil)
    let windowController    = storyboard.instantiateInitialController() as? NSWindowController
    let window              = windowController?.window

    windowController!.showWindow(self)

This will present the preferences view controller and when I drag it to another position and click the close button it will close. So far so good. However when I load the window again from the menu, it shows on it's original position instead of the position I last dragged the window to. Why is this?

Answer It appears to be a bug in xCode 7 setting the auto save name in code solved it.

    let storyboard          = NSStoryboard(name: "Preferences", bundle: nil)
    let windowController    = storyboard.instantiateInitialController() as? NSWindowController
    let window              = windowController?.window

    window!.setFrameAutosaveName("preferences")
    windowController!.showWindow(self)

Solution

  • This is a bug in Xcode 6 and I don't know if it is fixed in Xcode 7.

    Setting autosave in InterfaceBuilder has no effect. To get it to work just set its name in windowDidLoad() of your windowController:

    class MyWindowController: NSWindowController {
    
        override func windowDidLoad() {
            super.windowDidLoad()
    
            self.windowFrameAutosaveName = "position"
        }    
    }