Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 552
Mark Avatar asked Dec 02 '22 13:12

Mark


1 Answers

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"
    }    
}
like image 133
zisoft Avatar answered Dec 06 '22 09:12

zisoft