简体   繁体   中英

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)

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

Swift 4:

final class MyWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM