How to restore window position in an OSX applicati

2019-05-17 06:02发布

问题:

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)

回答1:

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"
    }    
}


回答2:

Swift 4:

final class MyWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        self.windowFrameAutosaveName = NSWindow.FrameAutosaveName(rawValue: "myWindow")
    }

}